Socket接收http请求

服务端socket:

public class HttpSocket {
    public static void main(String[] args) throws IOException {
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println("localhost:" + localHost);
        ServerSocket serverSocket = new ServerSocket(8080, 10, localHost); //初始化服务器的接口 backlog:10是允许客户端连接该服务端的总数

        System.out.println("服务器等待连接中......");
        Socket server = serverSocket.accept(); //服务器通信和客户端一样使用Socket类
        System.out.println("检测到客户端连接!");

        Thread accept = new Thread(new HttpAcceptThread(server));

        accept.start();
    }
}

接收消息线程类:

public class HttpAcceptThread implements Runnable{
    private Socket socket;

    public HttpAcceptThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            System.out.println("接收消息进程开启!");
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (!socket.isClosed()){
                try {
                    String s = reader.readLine();
                    System.out.println("[" + socket.getInetAddress().getHostAddress() + "] " + s);
                }catch (Exception e){
                    System.out.println("接收消息进程结束");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

浏览器发送本机IP+端口,请求Socket服务端:
Socket接收http请求_第1张图片

观察控制台输出:
Socket接收http请求_第2张图片

你可能感兴趣的:(Socket)