为了研究tcp连接建立过程,用java编写了一个tcp客户端(client),一个tcp服务端(Server)。程序的逻辑很简单,client连接server,向server发送消息,server收到消息作出响应,如果发送的消息是”close”字符串,双方关闭连接。

用抓包工具wireshark进行抓包,分析整个通信过程。

server

public class TcpServer {
    private final int SERVER_PORT = 8001;
    private ServerSocket servSocket;
    private Socket socket;
    public static void main(String[] args) throws Exception {
        TcpServer server = new TcpServer();
        server.acceptRequest();
    }
    /**
     * 接收客户端请求
     *
     * @throws Exception
     */
    public void acceptRequest() throws Exception {
        servSocket = new ServerSocket(SERVER_PORT);
        while (true) {
            System.out.println("准备接受请求....");
            socket = servSocket.accept();
            System.out.println("接收来自" + socket.getInetAddress().getHostName() + "的请求");
            while (true) {
                try {
                    InputStream in = socket.getInputStream();
                    int size;
                    byte[] msg = new byte[1024];
                    ByteArrayOutputStream bout = new ByteArrayOutputStream();
                    size = in.read(msg);
                    if (size == -1) {
                        System.out.println("关闭连接:" + socket.getInetAddress());
                        socket.close();
                        break;
                    }
                    bout.write(msg, 0, size);
                    String content = bout.toString();
                    bout.close();
                    System.out.println("接收到的报文为:");
                    System.out.println(content);
                    String response = "recived message:" + content;
                    socket.getOutputStream().write(response.getBytes("utf-8"));
                    socket.getOutputStream().flush();
                    System.out.println("报文已发送,等待接收");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    socket.close();
                    break;
                }
            }
        }
    }
}

Read the rest of this entry

,