【发布时间】:2021-09-24 21:46:23
【问题描述】:
我为客户端和服务器创建了两个不同的 java 类,每个类都有发送和接收方法。根据任务,我必须通过DatagramPacket 建立服务器到客户端的连接,并通过DatagramChannel 建立客户端到服务器的连接。最后一个效果很好,但是我在处理数据报时遇到了麻烦——它们是从服务器发送的,而客户端从来没有收到过。怎么了?
public class TransferClient implements Serializable{
private static final long serialVersionUID = 26L;
public TransferClient() {
}
public void send(Command com) throws IOException {
SocketAddress socketAddressChannel = new InetSocketAddress("localhost", 1);
DatagramChannel datagramChannel=DatagramChannel.open();
ByteBuffer bb;
datagramChannel.connect(socketAddressChannel);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(com);
oos.flush();
bb=ByteBuffer.wrap(baos.toByteArray(),0, baos.size());
datagramChannel.send(bb,socketAddressChannel);
baos.close();
oos.close();
}
public Command receive() throws IOException, ClassNotFoundException {
SocketAddress address = new InetSocketAddress(2029);
DatagramSocket s = new DatagramSocket();
DatagramPacket inputPacket = new DatagramPacket(new byte[1024],1024, address);
s.receive(inputPacket);
ByteArrayInputStream bais = new ByteArrayInputStream(inputPacket.getData());
ObjectInputStream ois = new ObjectInputStream(bais);
return (Command) ois.readObject();
}
}
public class TransferServer {
public TransferServer(){
}
public void send(Command com) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
byte[] buffer;
oos.writeObject(com);
oos.flush();
buffer=baos.toByteArray();
SocketAddress address = new InetSocketAddress("localhost",2029);
DatagramSocket s = new DatagramSocket();
DatagramPacket outputPacket = new DatagramPacket(buffer,buffer.length,address);
s.send(outputPacket);
}
public Command receive() throws IOException, ClassNotFoundException {
SocketAddress socketAddressChannel = new InetSocketAddress("localhost", 1);
DatagramChannel datagramChannel = DatagramChannel.open();
datagramChannel.bind(socketAddressChannel);
ByteBuffer bb = ByteBuffer.allocate(1024);
datagramChannel.receive(bb);
ByteArrayInputStream bais = new ByteArrayInputStream(bb.array());
ObjectInputStream ois = new ObjectInputStream(bais);
Command command;
System.out.println(ois.available());
command =(Command) ois.readObject();
datagramChannel.close();
ois.close();
bais.close();
return command;
}
}
【问题讨论】:
-
1024 以下的端口受到保护。看起来您使用的数字非常少。
-
哦,天哪,我更改了端口,但没有帮助。不过,谢谢!