我想通过UDP发送命令时读取字节流。我有以下代码:
import java.io.*;
import java.net.*;
public class udp_client
{
private static File fout = new File("data2.txt");
public static void main(String args[])
{
DatagramSocket sock = null;
int port = 10001;
String s;
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
try
{
sock = new DatagramSocket();
InetAddress host = InetAddress.getByName("192.168.0.2");
byte[] b = {(byte)0xf3,(byte)0xf2,(byte)0x02,(byte)0x01,(byte)0x00,(byte)0x00,(byte)0xfe,(byte)0x0e };
DatagramPacket dp = new DatagramPacket(b , b.length , host , port);
sock.send(dp);
//now receive reply
//buffer to receive incoming data
byte[] buffer = new byte[65536];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
sock.receive(reply);
byte[] data = reply.getData();
s = new String(data, 0, reply.getLength());
//echo the details of incoming data - client ip : client port - client message
echo(reply.getAddress().getHostAddress() + " : " + reply.getPort() + " - " + s);
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i=6;i<3078;i=i+3) {
//System.out.println(Integer.toHexString((data[k])));
System.out.println("hex="+Integer.valueOf(String.valueOf(data[k]), 16));
int r = (data[i] & 0xFF) | ((data[i+1] & 0xFF) << 8) | ((data[i+2] & 0x0F) << 16);
bw.write(Integer.toString(r));
bw.newLine();
//System.out.println("r["+i+"]="+r);
System.out.println(r);
//System.out.println(String.valueOf(data[i] & 0x00FF));
//JOptionPane.showMessageDialog(null, data[k]);
}
bw.close();
}
catch(IOException e)
{
System.err.println("IOException " + e);
}
}
//simple function to echo data to terminal
public static void echo(String msg)
{
System.out.println(msg);
}
}
问题是replyis 520的大小和数据应该在5000字节左右。如何阅读下一个数据?
答案 0 :(得分:0)
如果发件人正在发送长度为5000字节的数据包,那么receive(packet)
应该接收并完整地返回 ,前提是数据包中的缓冲区足够大。 (如果数据包缓冲区太小,则会截断该消息。另请参阅下面有关数据包丢失和碎片的警告。)
在您的情况下,接收缓冲区足够大以容纳5000字节的消息,这意味着发送方不发送该大小的UDP消息。
注意:建议不要将UDP用于发送大量数据。 UDP消息丢失,如果发生这种情况,接收方将不会收到通知。您发送的邮件越大,发生这种情况的可能性就越大。
当您发送的UDP消息不适合单个网络数据包时,它将被分解为片段。片段被重新组装到OS协议栈中的完整接收器中。但是,如果任何片段丢失,则无法重新组装UDP消息,操作系统将丢弃该消息(不通知)。
建议: