我正在编写简单的UDP客户端服务器。我必须在客户端使用DatagramChannel,在服务器端使用DatagramPacket。所以UDP不像TCP,我不得不检查来自服务器的消息。但是,当我没有收到数据包时,通道会无休止地等待,我应该使用什么?我尝试过如何通过DatagramSocket从DatagramChannel接收数据包,但是什么也没发生。
客户端
channel = DatagramChannel.open();
// channel.socket().setSoTimeout(timeout);
address = new InetSocketAddress("localhost", 2000);
//channel.configureBlocking(false);
channel.connect(address);
public ServerMessage doRequest(String command, Alice argument)throws IOException, ClassNotFoundException{
try {
ClientMessage message = new ClientMessage(command, argument);
sendedstreambuffer = new ByteArrayOutputStream();
sendedstream = new ObjectOutputStream(sendedstreambuffer);
sendedstream.writeObject(message);
sendedstream.flush();
ByteBuffer buffer = ByteBuffer.wrap(sendedstreambuffer.toByteArray());
buffer.flip();
channel.send(buffer, address);
buffer.clear();
channel.receive(buffer);
receivedsteam = new ObjectInputStream(new ByteArrayInputStream(buffer.array()));
return (ServerMessage) receivedsteam.readObject();
}catch (PortUnreachableException e){
return new ServerMessage(SpecialMessage.TIMEOUT, "===\nСервер не доступен.");
}
}
服务器端
DatagramSocket data = new DatagramSocket(2000);
while (true) {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
data.receive(packet);
receivedsteam = new ObjectInputStream(new ByteArrayInputStream(packet.getData()));
ClientMessage message = (ClientMessage) receivedsteam.readObject();
System.out.println(message.getMessage());
}