我制作了一个java ServerSocket。我使用套接字对象向它发送请求。请求将传递到ServerSocket,但响应不会返回。
服务器代码:
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();
}
客户代码:
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();
问题是程序卡在命令bufferStream.readLine()中。我通过输出行命令来检查请求是否到达服务器:SNDKEY并且它总是打印出来。但是密钥永远不会在用户端收到。
答案 0 :(得分:1)
bufferStream.readLine()
阻止,直到收到换行符。但是在服务器端,您输出PrintWriter.print()
,除非您告诉它,否则不会发送任何换行符。所以客户端永远等待。将print更改为println,或在邮件末尾添加换行符:
out.print("12345678901234567890\n");
如果您不想在协议中使用换行符,则可以在读取每个字节后或读取特定字节数后使用bufferStream.read
而不是bufferStream.readLine
返回。