how to send an int through UDP in java
Asked Answered
C

3

6

I'm trying to write a bit of code which sends a single int over UDP. The code I have so far:

Sender:

int num = 2;

DatagramSocket socket = new DatagramSocket();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream pout = new PrintStream( bout );
pout.print(num);
byte[] barray = bout.toByteArray();
DatagramPacket packet = new DatagramPacket( barray, barray.length );
InetAddress remote_addr = InetAddress.getByName("localhost");           
packet.setAddress( remote_addr );
packet.setPort(1989);
socket.send( packet );

Receiver:

        DatagramSocket socket = new DatagramSocket(1989);
        DatagramPacket packet = new DatagramPacket(new byte[256] , 256);

        socket.receive(packet);

        ByteArrayInputStream bin = new ByteArrayInputStream(packet.getData());

        for (int i=0; i< packet.getLength(); i++)
        {
        int data = bin.read();
        if(data == -1)
        break;
        else
        System.out.print((int) data);

The problem is the receiver is printing '50' to screen which is obviously not right. I think that the problem may be that I'm somehow sending it as a string or something and its not reading it right. Any help?

Chios answered 8/3, 2011 at 18:21 Comment(0)
P
8

Use data streams like:

import java.io.*;

public class Main {
    public static void main(String[] args) throws Exception {
        final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        final DataOutputStream dataOut = new DataOutputStream(byteOut);
        dataOut.writeInt(1);
        dataOut.writeDouble(1.2);
        dataOut.writeLong(4l);
        dataOut.close(); // or dataOut.flush()
        final byte[] bytes = byteOut.toByteArray();
        final ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
        final DataInputStream dataIn = new DataInputStream(byteIn);
        final int integ = dataIn.readInt();
        final double doub = dataIn.readDouble();
        final long lon = dataIn.readLong();
        System.out.println(integ);
        System.out.println(doub);
        System.out.println(lon);
    }

}

Pericycle answered 8/3, 2011 at 18:49 Comment(0)
B
2

InputStream.read() returns a single byte, not a 32-bit integer (see javadoc). So what you want is

ObjectInputStream os = new ObjectInputStream(bin);
os.readInt();
Bumbledom answered 8/3, 2011 at 18:29 Comment(0)
S
1

The problem is that you're receiving CHAR CODE of '2' and not acctual 2 as integer. Try changing the your receiver code to:

    DatagramSocket socket = new DatagramSocket(1989);
    DatagramPacket packet = new DatagramPacket(new byte[256] , 256);

    socket.receive(packet);

    System.out.print(new String(packet.getData()));

But ObjectInputStream solution would work better for you I guess.

Smithers answered 8/3, 2011 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.