1
我有一個代碼來發送和接收UDP套接字保存UDP套接字數據到文件
發送UDP代碼:
public static void main(String args[]) throws Exception
{
try
{
FileOutputStream fo = new FileOutputStream("OUTFILE.txt");
PrintStream ps = new PrintStream(fo);
DatagramSocket Socket = new DatagramSocket(4555);
byte[] receiveData = new byte[1000000];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
while(true)
{
receivePacket.setLength(receiveData.length);
Socket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
System.out.printf("RECEIVED: %s " , new String(receivePacket.getData()));
ps.println(sentence);
ps.println();
ps.close();
fo.close();
}
File file = new File("OUTFILE.txt");
FileInputStream fis = new FileInputStream(file);
byte[] fsize = new byte[(int) file.length()];
int size = fis.read(fsize);
System.out.println("Received Size = " + size);
}
catch (Exception e) {
System.err.println(e);
}
}
}
我想寫每個值接收到的數據包進入文件,然後獲取整個文件的大小。 在我的代碼中,我剛剛得到了寫入文件的第一個接收值。 您能否告訴我如何在文件中寫入整個收到的值?
謝謝內特,但它通過移動.close()簡化版,工作外的loop.I嘗試這個條件來停止循環 \t如果(receivePacket.getLength()== 0) \t \t休息; \t \t \t但它不停止循環 –
這不是一個有效的方法來打破循環。閱讀JavaDoc for ['DatagramSocket.receive()'](http://docs.oracle.com/javase/6/docs/api/java/net/DatagramSocket.html#receive(java.net.DatagramPacket)): 「這種方法阻塞直到收到數據報,數據報包對象的長度字段包含接收到的消息的長度。」 – Nate
你可以üPLZ給我一個提示如何停止循環? –