gpt4 book ai didi

java - 客户端不接收来自服务器 DataOutputStream 的输出

转载 作者:可可西里 更新时间:2023-11-01 02:39:53 26 4
gpt4 key购买 nike

我目前正在尝试编写我的第一个客户端>服务器系统以通过网络来回传输包含字符串的数据包。但是我遇到了以下问题:客户端向服务器发送消息,服务器收到消息,处理消息,然后理应向客户端发送回复,但客户端从未收到此消息并挂起等待服务器的响应。这是代码:

服务器:

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 "";
}

最佳答案

客户端正在调用 readLine() 但服务器没有写入一行,只是写入字节,因此客户端一直在等待行终止符。将 '\n' 附加到服务器的回复。服务器也应该在完成后关闭接受的套接字。通过关闭您包裹在它周围的任何编写器或输出流来执行此操作,而不是关闭套接字本身。

您应该使用 BufferedOutputStream 而不是 DataOutputStream。它可以按原样处理简单数据,但如果您迟早不修复它,则可能会遇到字符集问题。通常,您应该始终使用对称输入和输出流或读取器。

关于java - 客户端不接收来自服务器 DataOutputStream 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14680320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com