Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package udp.test;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.nio.ByteBuffer;
- /**
- *
- * @author Adam
- */
- public class Server_UDP_Thread_Monitor implements Runnable
- {
- // UDP Socket
- private DatagramSocket socket;
- // UDP Read Byte Buffer
- private ByteBuffer readBuffer = ByteBuffer.allocate(512);
- // Keep thread alive
- private boolean monitor = true;
- @Override
- public void run()
- {
- try
- {
- this.socket = new DatagramSocket(3889);
- this.socket.setSoTimeout(1000);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- while (this.monitor)
- {
- try { this.readPacket(); } catch (Exception e) { continue; }
- }
- }
- /**
- * @throws IOException
- */
- private void readPacket() throws IOException
- {
- this.readBuffer.clear();
- DatagramPacket packet = new DatagramPacket(this.readBuffer.array(), this.readBuffer.array().length);
- this.socket.receive(packet);
- // Do something with data here
- }
- /**
- * @param packet
- * @throws IOException
- */
- public synchronized void send(DatagramPacket packet) throws IOException
- {
- this.socket.send(packet);
- }
- /**
- * @param s
- */
- public void setMonitorState(boolean s)
- {
- this.monitor = s;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement