我正在使用套接字在服务器和客户端之间进行通信。 但是出于某种原因,客户端会跳过服务器发送的每隔一行。
客户代码:
...
out.println(console.readLine()); //Client initiates (sent to server)
while ((userOut = in.readLine()) != null) //Waits for response
{
System.out.println("Server says: " + userOut); //Prints response
userIn = console.readLine(); //Gets user input
out.println(userIn); //Sends user input to server
}
...
服务器代码:
...
while ((clientIn = in.readLine()) != null) //Waits for clients message
{
System.out.println("Client says: " + clientIn); //Print clients message
//Send appropriate response
if (clientIn.equals(CLIENT_INSTRUCTION_LOGCALC))
{
out.println(SERVER_RESPONSE_LOGCALC_OK); //Send response to client
System.out.println("Message sent: " + SERVER_RESPONSE_LOGCALC_OK); //Print response sent
}
else if (clientIn.equals(CLIENT_INSTRUCTION_SB))
{
out.println(SERVER_RESPONSE_SB_CHANGE);
}
else if (clientIn.equals(CLIENT_INSTRUCTION_BYE))
{
out.println(SERVER_RESPONSE_BYE_OK);
}
else if (clientIn.equals(CLIENT_INSTRUCTION_END))
{
out.println(SERVER_RESPONSE_END_OK);
}
else
{
out.println(SERVER_RESPONSE_INPUT_ERR);
}
...
使用此显示的示例(客户端优先):
LOGCALC
Server says: LOGCALC: OK
LOGCALC
Server says:
服务器:
Client says: LOGCALC
Message sent: LOGCALC: OK
Client says: LOGCALC
Message sent: LOGCALC: OK
希望您可以看到在发送给服务器的第二条LOGCALC消息中,服务器已响应,但客户端未收到服务器响应。
有什么想法吗?
答案 0 :(得分:1)
客户端肯定会收到“某种”消息,因此打印出“服务器说”部分。似乎服务器在向客户端发送“第一个响应”时会以某种方式写入额外的新行,导致在第二次迭代时读取空字符串。在第二种情况下检查/调试userOut
的值是值得的。
另外,我不确定它是否是故意的,但是在服务器输出的情况下我看到一个空行。假设它是发布的代码片段进行所有输出,那么额外的换行来自哪里?
答案 1 :(得分:0)
的readLine()
仅扫描\ r \ n,仅扫描\ r \ n或仅扫描\ n。
我认为,服务器可以通过\ n \ r-linebreak回答,在这种情况下,你将成为你的双线(一个用于\ n,另一个用于\ r)。
据我所知,这可能不是代码功能的问题。 因此,要跳过日志记录问题:您可以检查空userOut(通过清空检查)。
答案 2 :(得分:0)
查看您的输出,似乎您在SERVER_RESPONSE_LOGCALC_OK
中有一个额外的换行符,因为System.out.println("Message sent: " + SERVER_RESPONSE_LOGCALC_OK);
在服务器输出中有一个额外的行。我会删除额外的换行符或使用简单的out.print(SERVER_RESPONSE_LOGCALC_OK)
代替out.println(SERVER_RESPONSE_LOGCALC_OK);
。这应该可以解决您的跳过问题。
您遇到的潜在缺陷是因为您只能一次读取一行然后在读取另一行之前等待用户输入,而不是等待用户输入之前可用的行数。我敢打赌,如果你在客户端做类似下面的代码,你会看到不同的输出。
out.println(console.readLine()); //Client initiates (sent to server)
while ((userOut = in.readLine()) != null) //Waits for response
{
System.out.println("Server says: " + userOut); //Prints response
if(!in.available()){
userIn = console.readLine(); //Gets user input
out.println(userIn); //Sends user input to server
}
}