我想创建一个Java服务器套接字应用程序,它接收TCP数据包并读取它的内容。根据数据包的内容,它将执行多个操作。我设法达到了读取一些内容并打印字符串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();
}
}