我目前正在尝试编写我的第一个客户端>服务器系统来通过网络来回传输包含字符串的数据包。但是我遇到了以下问题:客户端向服务器发送消息,服务器接收消息,处理消息,然后应该向客户端发送回复,但客户端从未收到此消息并且挂起等待来自服务器的响应。这是代码:
服务器:
public static void handlePackets() throws Exception {
String clientSentence;
String returnToClient;
ServerSocket welcomeSocket = new ServerSocket(1337);
System.out.println("Packet receiver initialized!");
while (run) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received Packet: " + clientSentence);
System.out.println("Compiling return to client.");
returnToClient = "";
if (clientSentence.startsWith("Handshake-")) {
returnToClient = handleHandShake(clientSentence);
}
outToClient.writeBytes(returnToClient);
System.out.println("Sent client response " + returnToClient);
}
welcomeSocket.close();
}
客户:
public static String sendTCP(String host, String content) {
try {
System.out.println("Packet sender sending TCP packet " + content);
String serverResponse;
Socket clientSocket = new Socket(host, 1337);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(content + '\n');
System.out.println("Send data to sever. Awaiting response.");
serverResponse = inFromServer.readLine();
clientSocket.close();
System.out.println("Server response received " + serverResponse + " result was returned to caller.");
return serverResponse;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}