title: Java DatagramSocket throws a SocketTimeoutException after a few runs
body: <p>I am writting a Java application that reads game server information. That's all it does, it runs in a loop doing the same thing.</p>
  
  <p>The problem is that at first it works great, I get a response. After some(not a constant number) times it starts throwing the SocketTimeoutException.</p>
  
  <p>This is the method I use for querying a SAMP server.</p>
  
  <pre><code>    private ByteBuffer sendQuery(char opcode) throws IOException {
  
      ByteBuffer bf = ByteBuffer.allocate(11);
      bf.order(ByteOrder.LITTLE_ENDIAN);
      bf.put("SAMP".getBytes("US-ASCII"));
      bf.put(encodeIP(getIp()));
      bf.putShort((short)getPort());
      bf.put((byte)opcode);
      Logger.getLogger().log("Request to " + this.getAddress().getHostString() + ":"+ByteConvert.bytesToHexString(bf.array()));
  
      DatagramPacket packet = new DatagramPacket(bf.array(), bf.capacity(), getAddress().getAddress(), getPort());
      getSocket().send(packet);
  
      byte[] buffer = new byte[4096];
      packet = new DatagramPacket(buffer, buffer.length, getAddress().getAddress(), getPort());
      getSocket().receive(packet);
      if(packet.getLength() &gt; 4096)
          Logger.getLogger().log("Large packet received from " + this.getIp() + " :"+packet.getLength());
      bf = ByteBuffer.allocate(packet.getLength());
      bf.order(ByteOrder.LITTLE_ENDIAN);
      bf.put(buffer, 0, packet.getLength());
      bf.flip();
      return bf;
  }
  </code></pre>
  
  <p><code>encodeIP</code> method:</p>
  
  <pre><code>private static byte[] encodeIP(String s) throws IOException {
      String[] ip = s.split("\\.");
      byte[] bytes = new byte[ip.length];
      for(int i = 0; i &lt; ip.length; i++) {
          bytes[i] = (byte)Integer.parseInt(ip[i]);
      }
      return bytes;
  }
  </code></pre>
  
  <p>The protocol is documented <a href="http://wiki.sa-mp.com/wiki/Query_Mechanism" rel="nofollow">here</a>.</p>
  
  <p>Other games have the same issue but currently i'm investigating SAMP as its protocol seems to be the simplest.</p>
  
  <p>The application is running on Linux, Debian 7.0. I tried disabling the firewall completely. </p>