Java web learning journey - java socket programming (request and response principle)

Keywords: socket Java

Request step (client)

  1. Create socket connection through host and port
  2. Get the output stream in socket and write the request data to the output stream
  3. Get the input stream in the socket and read the response data in the input stream

Response steps (server)

  1. Establish listening port and wait for TCP connection request
  2. Get the input stream in the socket and read the response data in the input stream
  3. Get the output stream in socket and write the request data to the output stream

summary

The client and the server communicate through the input and output streams in the socket.

Client code

package com.my.test.web;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author lf
 * @Title: MyHttpClient
 * @Description: java socket Client
 * @date 2019/4/1 14:52
 */
public class MyHttpClient {

    public static void main(String[] args) throws Exception{
        String uri = "index.html";
        doGet("127.0.0.1",8080,uri);
    }

    private static void doGet(String host, int port, String uri) throws Exception{
        //1. Establish socket connection
        Socket socket = new Socket(host, port);
        //2. Get output stream write request data from socket
        StringBuffer requsetInfo = new StringBuffer();
        requsetInfo.append("GET "+uri+" HTTP/1.1\r\n");//Request first line
        requsetInfo.append("Accept: */*\r\n");//Request header information
        /*
        * requestInfo.append(.....);
        * */
        OutputStream socketOut = socket.getOutputStream();
        socketOut.write(requsetInfo.toString().getBytes());
        //3. Get input stream from socket to read response data
        InputStream socketIn = socket.getInputStream();
        int size = socketIn.available();
        byte[] buffer = new byte[size];
        socketIn.read(buffer);

        String responseStr = new String(buffer);
    }
}

Server code

package com.my.test.web;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author lf
 * @Title: MyHttpServer
 * @Description: java socket http Server side
 * @date 2019/4/1 14:35
 */
public class MyHttpServer {

    public static void main(String[] args) throws Exception{
        int port = 8080;
        //1. Listen to port 8080
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Server listening"+port+"Port, waiting for client request");
        //2. Wait for customer connection
        while (true){
            Socket socket = serverSocket.accept();
            System.out.println("Client and service are connected! Client side ip yes:"+socket.getInetAddress());
            //3. Processing request
            service(socket);
        }
    }

    /**
      * @Description: Processing request
      * @author lf
      * @date 2019/4/1 14:42
      */
    private static void service(Socket socket) throws Exception{
        //Get input stream read request data from input stream
        InputStream socketIn = socket.getInputStream();
        int size = socketIn.available();
        byte[] buffer = new byte[size];
        socketIn.read(buffer);
        String requsetStr = new String(buffer);

        /*
        * Parsing data in requests and requested resources
        * */

        //
        OutputStream socketOut = socket.getOutputStream();
        String responseFirstLine = "HTTP/1.1 200 OK\r\n";
        String responseHeader = "Content-Type:text\\html";
        socketOut.write(responseFirstLine.getBytes());
        socketOut.write(responseHeader.getBytes());

        //Close socket
        socket.close();
    }

}

Posted by briansol on Thu, 05 Dec 2019 20:42:39 -0800