【发布时间】:2018-07-08 13:38:35
【问题描述】:
服务器和客户端之间的通信有问题。我试图找出一种自动通信的方式,因为它们必须交换一些参数。但是,使用我编写的代码,服务器要么在客户端确认消息后继续向客户端发送相同的消息,要么客户端什么也没收到。插座和所有东西之前都已经设置好了。两个代码示例中的函数 sendString() 和 receiveString() 是相同的。有没有正确的方法来做到这一点?我不明白为什么这不起作用...
服务器:
String buffer;
while(true){
buffer = client.receiveString();
if(buffer != null && buffer.equals("ready")){
System.out.println("Client is ready");
client.sendString("ready");
while(true){
buffer = client.receiveString();
if(buffer != null && buffer.equals("k")){
System.out.println("stopped");
break;
}
}
break;
}
}
public String receiveString() throws IOException{ //From the client class
if(dataIn.available() > 0){
int length = dataIn.readInt();
byte[] b = new byte[length];
dataIn.readFully(b, 0, b.length);
return new String(b, Charset.forName("UTF-8"));
}
return null;
}
public void sendString(String msg) throws IOException{
byte[] b = msg.getBytes(Charset.forName("UTF-8"));
dataOut.writeInt(b.length);
dataOut.write(b);
}
客户:
String buffer;
while(true){
sendString("ready");
buffer = receiveString();
if(buffer!=null)
System.out.println(buffer);
if(buffer != null && buffer.equals("ready")){
System.out.println("Server is ready");
sendString("k");
break;
}
}
【问题讨论】:
-
猜测:dataIn.available() 是一个非阻塞调用。因此,您的客户基本上会发送“就绪”,检查是否有答案(可能不是这样),然后立即再次发送就绪。尝试删除 if(dataIn.available() > 0) 条件并等待您的服务器响应。
标签: java sockets datainputstream