Search code examples
javaudpdatagram

How to transfer an int via DatagramSocket


I wanna do a simple application to transfer integers via DatagramSockets, but I didn't want to do workarounds like using Strings and casting them to int, I'd rather know if there is a adhoc way to pass integers via DatagramSocket.

//sender side
public void Send() throws Exception {
    DatagramSocket socket = new DatagramSocket(3000);
    int x = 5;
    DatagramPacket sendPacket = ...
    socket.send(sendPacket);
}

//reeceiver side
public void Receive() throws Exception {
    DatagramSocket socket = new DatagramSocket(2000);
    DatagramPacket receivePacket = ...
    socket.receive(receivePacket);  
    int x = (int) receivePacket;
}

Part of this code is just to demonstrate what I want. I'd like to know how to write an int in the sender side and how to read this int in the receiver side.


Solution

  • Use a ByteBuffer.

    SocketAddress address = ...
    int value = ...
    
    byte[] buf = ByteBuffer.allocate(Integer.BYTES).putInt(value).array();
    socket.send(new DatagramPacket(buf, buf.length, address));