title: java udp packet merging
body: <p>I've got a strange problem while practising with UDP in Java.  If I send multiple UDP handshake packets of different data lengths between servers, the UDP packets merge.  I'm using a timer to send the handshakes between the servers.</p>
  <pre><code>public class UDPtest {
  
  public static UDPtest test = new UDPtest();
  public static byte[] buffer = new byte[1024];
  public static InetAddress host = null;
  Timer timer = new Timer();
  TimerTask ttimer = new TimerTask() {
      public void run() {
      //System.out.println(&quot;time&quot;);
      }   
  };
  
  public static void main(String args[]) throws Exception {
      DatagramSocket sendSocket = new DatagramSocket();
      DatagramSocket receiveSocket = new DatagramSocket(Integer.parseInt(args[1]));
      String s = &quot;SEND &quot;+args[0];
      host = InetAddress.getByName(&quot;localhost&quot;);
      buffer = s.getBytes();
      DatagramPacket handshake = new DatagramPacket(buffer, buffer.length, host, Integer.parseInt(args[2])); 
      test.RouteTimer(receiveSocket,handshake);
  
  
  while (true) {
          DatagramPacket receivePacket = new DatagramPacket(buffer,buffer.length);
          receiveSocket.receive(receivePacket);
          String receiveString = new String(receivePacket.getData());
  
          if (receiveString.substring(0,1).matches(&quot;A&quot;)) {
          
              System.out.println(receiveString);
              continue;
  
          }
          else {
          
              System.out.println(receiveString);
              String temp = &quot;A &quot;+args[0];
              buffer = temp.getBytes();
              DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, host, Integer.parseInt(args[2]));
              sendSocket.send(sendPacket);
          }
      }
      
  }
  
  public void RouteTimer(final DatagramSocket socket, final DatagramPacket handshake) {
      Timer timer = new Timer();
      TimerTask ttimer = new TimerTask() {
          @Override
          public void run() {
                      try {
                      socket.send(handshake);         
                      }
                      catch (Exception e) {
                      
                      }
          }
      };
      
  timer.scheduleAtFixedRate(ttimer, 1000, 5000);
  }
  
  }
  </code></pre>
  <p>For example: If I have server X and Y, the expected output for server X would be:</p>
  <blockquote>
  <p>SEND X</p>
  <p>A X</p>
  <p>SEND X</p>
  <p>A X</p>
  </blockquote>
  <p>but the output becomes:</p>
  <blockquote>
  <p>SEND Y</p>
  <p>A Y</p>
  <p>SEN</p>
  <p>A Y</p>
  </blockquote>
  <p>I'm trying to understand why this happens, and how to fix the problem.
  Any help would be appreciated.</p>