How to send int via UDP in java

I am trying to write some code that sends one int on top of UDP. The code I have so far is:

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

Recipient:

  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 that the receiver prints โ€œ50โ€ on the screen, which is obviously not true. I think the problem may be that I am somehow sending it as a string or something else, but I am not reading it correctly. Any help?

+6
java udp datagram
source share
3 answers

Use data streams, for example:

 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 = byteOutStream.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); } 

}

+8
source share

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

 ObjectInputStream os = new ObjectInputStream(bin); os.readInt(); 
+2
source share

The problem is that you are getting CHAR CODE of '2', not acctual 2 as a whole. Try changing 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 an ObjectInputStream solution will work better for you, I think.

+1
source share

All Articles