我正在编写一个使用 DatagramSocket (UDP) 发送文件的客户端,但首先我们需要使用 writeUTF() 将文件名发送到服务器。客户端和服务器都编译和运行没有任何错误,但文件名似乎永远不会到达服务器。知道会发生什么吗?我在下面发布代码...
谢谢 :)
客户端.java
...
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = fis.read(buf)) != -1;)
{
bos.write(buf, 0, readNum); //no doubt here is 0
}
// File data
byte[] data = bos.toByteArray();
DataOutputStream dos = new DataOutputStream(bos);
//file is a String with the name of the file
dos.writeUTF(file);
//Setting up DatagramSocket
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
socket.send(packet);
...
服务器.java
...
almacen = new byte[MAXNOMBREFICHERO + 2];
packet = new DatagramPacket( almacen, almacen.length );
System.out.println("\nWaiting client...");
socket.receive(packet);
dirIPClient = packet.getAddress();
clientPort = packet.getPort();
ByteArrayInputStream bais = new ByteArrayInputStream( almacen );
DataInputStream dis = new DataInputStream( bais );
filename = dis.readUTF();
...