How to add a sequence number to a datagram packet in java over a UDP connection?

Viewed 701

I cant figure out how to attach a sequence number to a datagram packet over a UDP connection. See code below:


public class Client {

    public static void main(String args[]) throws Exception
    {
        
        DatagramSocket clientSocket = new DatagramSocket();
        InetAddress IPAddress = InetAddress.getByName("localhost");
        Integer SN = 1;
        
    // create byte arrays for sending and receiving data
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];

        
    // file reader
        FileReader fr = new FileReader("umbrella.txt");
        BufferedReader br = new BufferedReader(fr);
        String fileText;
        fileText = br.readLine();
        System.out.println(fileText);

    // convert to bytes
        byte [] fileBytes = fileText.getBytes();
        //byte [] seqNumBytes = ByteBuffer.allocate(4).putInt(SN).array();
        
    //concatenate sequence number with file:
        
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
        DataOutputStream dos = new DataOutputStream(outputStream);
        dos.write( fileBytes );
        dos.writeInt(SN);
        
        byte [] concatData = outputStream.toByteArray( );
        
        sendData = concatData;

    // send packet
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 102);
        clientSocket.send(sendPacket);

As can be seen ive tried to concatenate the sequence number (SN) which is set to 1.

When I run the server and client my server picks up the text file and simply returns the contents without the sequence number.

see particularly this snip:


//concatenate sequence number with file:
        
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
        DataOutputStream dos = new DataOutputStream(outputStream);
        dos.write( fileBytes );
        dos.writeInt(SN);
        
        byte [] concatData = outputStream.toByteArray( );
        
        sendData = concatData;

How do I attach a sequence number to each datagram packet and have that read on the server side?

0 Answers
Related