0

我想创建一个接收 TCP 数据包并读取其内容的 Java 服务器套接字应用程序。根据数据包的内容,它将执行几个动作。我设法让它读取一些内容并打印一个字符串 System.out.println(sb.toString()); 但是 (a) 并非所有内容都已打印,并且 (b) 我不确定当内容按网络顺序到达时如何处理它们。一个示例是接收 HTTP 数据包并从标头报告“Content-Length”或“User-Agent”。任何示例将不胜感激。

public static void main(String[ ] args){

PrintWriter out = null;
BufferedReader in = null;
int bufferSize = 0;


try{
    String message = args[0];
    int count = 0;

    ServerSocket connectionSocket = null;
    try {
        connectionSocket = new ServerSocket(4444);
        System.out.println("Server started");
    } catch (IOException e) {
        System.err.println("Could not listen on port: 4444.");
        System.exit(1);
    }

    Socket clientSocket = null;
    try {
        while(true){
            count++;
            clientSocket = connectionSocket.accept();
            System.out.println("TCP packet received… " +  count);
            InputStream is = clientSocket.getInputStream();

            out = new PrintWriter(clientSocket.getOutputStream());
            in = new BufferedReader(new InputStreamReader(is));

            StringBuilder sb = new StringBuilder();
            String line = null;


            while ((line = in.readLine()) != null) {
                sb.append(line + "\n");
            }
            System.out.println(sb.toString());


            clientSocket.close();
        }           
    } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
    }
}
catch(Exception e){
    e.printStackTrace();
}
}
4

0 回答 0