DatagramSocket serverSocket = new DatagramSocket(8888);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
//接收文件信息,包括文件名,文件长度。
serverSocket.receive(receivePacket);
String fileName = new String(receivePacket.getData()).trim();
System.out.println("FileInfor: " + fileName);
fileName = fileName.split("\\.")[0] + "New." + fileName.split("\\.")[1];
System.out.println("NewFileName" + fileName);
FileWriter fileWriter = new FileWriter(fileName);
while(true){
receivePacket.setData(receiveData);
serverSocket.receive(receivePacket);
String filecon = new String(receivePacket.getData());
System.out.println("文件内容:" + filecon);
if(filecon.trim().equals("end")){
fileWriter.close();
break;
}
fileWriter.write(filecon);
fileWriter.flush();
}
serverSocket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
上面是我写的 UDP 服务端,当第二次接收消息的时候,由于第一次数组并没有清空,所以,后面接收的数据就有问题。有谁知道这个怎么解决么?
------解决方案--------------------
while(true)里每次重新
receiveData = new byte[1024];初始化一下存放数据的数组不就可以了
------解决方案--------------------
receivePacket有getLength方法可以获取收到或发出的信息的长度.
在处理getData前先把收到的长度取出来,然后根据长度去读取数组中的数据就可以了.
具体可以查看DatagramPacket的API