服务器和客户端之间的通讯出现问题。我试图找出一种自动通信的方式,因为它们必须交换一些参数。但是,使用我编写的代码,服务器要么在客户端确认消息后继续向客户端发送相同的消息,要么客户端什么也没收到。套接字和所有东西都已经设置好了。函数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; }}
添加回答
举报
0/150
提交
取消