Advertisement
Guest User

Untitled

a guest
Mar 20th, 2011
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1.  
  2. package udp.test;
  3.  
  4. import java.io.IOException;
  5. import java.net.DatagramPacket;
  6. import java.net.DatagramSocket;
  7. import java.nio.ByteBuffer;
  8.  
  9.  
  10. /**
  11.  *
  12.  * @author Adam
  13.  */
  14. public class Server_UDP_Thread_Monitor implements Runnable
  15. {
  16.     // UDP Socket
  17.     private DatagramSocket socket;
  18.  
  19.     // UDP Read Byte Buffer
  20.     private ByteBuffer readBuffer = ByteBuffer.allocate(512);
  21.  
  22.     // Keep thread alive
  23.     private boolean monitor = true;
  24.  
  25.     @Override
  26.     public void run()
  27.     {
  28.         try
  29.         {
  30.             this.socket = new DatagramSocket(3889);
  31.             this.socket.setSoTimeout(1000);
  32.         }
  33.         catch (Exception e)
  34.         {
  35.             e.printStackTrace();
  36.         }
  37.  
  38.         while (this.monitor)
  39.         {
  40.             try { this.readPacket(); } catch (Exception e) { continue; }
  41.         }
  42.     }
  43.    
  44.     /**
  45.      * @throws IOException
  46.      */
  47.     private void readPacket() throws IOException
  48.     {
  49.         this.readBuffer.clear();
  50.  
  51.         DatagramPacket packet = new DatagramPacket(this.readBuffer.array(),      this.readBuffer.array().length);
  52.  
  53.         this.socket.receive(packet);
  54.  
  55.         // Do something with data here
  56.     }
  57.  
  58.     /**
  59.      * @param packet
  60.      * @throws IOException
  61.      */
  62.  
  63.     public synchronized void send(DatagramPacket packet) throws IOException
  64.     {
  65.         this.socket.send(packet);
  66.     }
  67.  
  68.     /**
  69.      * @param s
  70.     */
  71.     public void setMonitorState(boolean s)
  72.     {
  73.         this.monitor = s;
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement