javac31 javac31 - 1 month ago 26
Java Question

UDP Reading stream of bytes

I want to read a stream of bytes when sending a command through UDP. I have the following code:


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(;

sock = new DatagramSocket();

InetAddress host = InetAddress.getByName("");

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);

//now receive reply
//buffer to receive incoming data
byte[] buffer = new byte[65536];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);


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("hex="+Integer.valueOf(String.valueOf(data[k]), 16));
int r = (data[i] & 0xFF) | ((data[i+1] & 0xFF) << 8) | ((data[i+2] & 0x0F) << 16);
//System.out.println(String.valueOf(data[i] & 0x00FF));
//JOptionPane.showMessageDialog(null, data[k]);

catch(IOException e)
System.err.println("IOException " + e);

//simple function to echo data to terminal
public static void echo(String msg)

the problem is that size of the replyis 520 and the data should be around 5000 bytes. How can I read the next data?


If the sender is sending packets that are 5000 bytes long, then the receive(packet) should receive and return them in their entirety provided that the buffer in the packet is large enough. (If the packet buffer is too small, the message will be truncated. Also, see caveats below about packet loss and fragmentation.)

In your case, the receive buffer is large enough to hold a 5000 byte message, so that implies that the sender is not sending UDP messages of that size.

Note: UDP is not recommended for sending large amounts of data. UDP messages get lost, and the receiver gets no notification if this occurs. The larger the message you send, the more likely it is that this will occur.

When you send a UDP message that won't fit into a single network packet, it will be broken up into fragments. The fragments are reassembled into the complete receiver in the OS protocol stack. However, if any of the fragments gets lost, the UDP message cannot be reassembled, and will be discarded by the OS (without notification).


  • If you need reliability, use TCP rather than UDP.
  • Avoid sending large UDP messages.