title: how to send an int through UDP in java
body: <p>I'm trying to write a bit of code which sends a single int over UDP. The code I have so far:</p>
  
  <p>Sender:</p>
  
  <pre><code>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 );
  </code></pre>
  
  <p>Receiver:</p>
  
  <pre><code>        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&lt; packet.getLength(); i++)
          {
          int data = bin.read();
          if(data == -1)
          break;
          else
          System.out.print((int) data);
  </code></pre>
  
  <p>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?</p>