[英]SocketServer and Socket Communication, Answer Not received
I have made a java ServerSocket. 我做了一个Java ServerSocket。 I send a request to it using a Socket Object.
我使用套接字对象向其发送请求。 The request is delivered to the ServerSocket but the response does not come back.
该请求将传递到ServerSocket,但不会返回响应。
Server Code : 服务器代码:
Socket startserver = this.wifiserver.accept();
in = new InputStreamReader(startserver.getInputStream());
BufferedReader read = new BufferedReader(in);
String request = read.readLine();
//System.out.println(request);
if(request.equals("SNDKEY")){
System.out.println("Command is: SNDKEY");
out = new PrintWriter(startserver.getOutputStream());
out.print("12345678901234567890");
out.close();
}
Client Code: 客户代码:
Socket connection = new Socket( ip, port );
writeServer = new PrintWriter(connection.getOutputStream());
inputStream = new InputStreamReader(connection.getInputStream());
bufferStream = new BufferedReader(inputStream);
writeServer.print("SNDKEY");
this.Key = bufferStream.readLine();
The problem is that the program gets stuck at the command bufferStream.readLine(). 问题是程序卡在了命令bufferStream.readLine()上。 I have checked that the request is reaching the server by outputing the line command is: SNDKEY and it always gets printing out.
我已经通过输出以下行命令来检查请求是否已到达服务器:SNDKEY,它总是打印出来。 But the key is never received at the user end.
但是密钥永远不会在用户端收到。
bufferStream.readLine()
blocks until a newline is received. bufferStream.readLine()
阻塞,直到收到换行符为止。 But on the server side you are outputting with PrintWriter.print()
, which doesn't send any newlines unless you tell it to. 但是在服务器端,您将使用
PrintWriter.print()
输出,除非您告知,否则不会发送任何换行符。 So the client waits forever. 因此,客户永远等待。 Either change the print to println, or add a newline character to the end of the message:
将打印更改为println,或在消息末尾添加换行符:
out.print("12345678901234567890\n");
When you don't want to use newlines in your protocol, you could alternatively use bufferStream.read
instead of bufferStream.readLine
to return after reading each byte or after reading a specific number of bytes. 当您不想在协议中使用换行符时,可以选择使用
bufferStream.read
而不是bufferStream.readLine
在读取每个字节或读取特定数目的字节后返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.