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?
java udp datagram
user650309
source share