UDP Server Thread in Java


This is a thread class I wrote to handle UDP packets as they are received. It serves as a producer-thread. It takes the packet and puts it in a BlockingQueue for a consumer-thread to pickup and record.

public class LogUDPThread extends Thread {

    protected DatagramSocket socket = null;
    protected boolean listen = true;

    public LogUDPThread() throws IOException {
        this("UDPThread");
    }

    public LogUDPThread(String name) throws IOException {
        super(name);
        socket = new DatagramSocket(4445);
    }

    public void run() {
        byte[] buf = new byte[10000];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        
        while (listen) {
            try {
                // receive request
                socket.receive(packet);
                
                // figure out response
                String packetData = new String(packet.getData(), "UTF8");
                RawLog log = new RawLog();
                log.dataString = packetData;
                log.timestamp = new Date();
                log.sourceAddress = packet.getAddress().getHostAddress();
                log.sourceName = packet.getAddress().getCanonicalHostName();
                log.sourceType = "UDP";
                
                Main.messagesToLog.add(log);

            } catch (Exception e) {
                e.printStackTrace();
                listen = false;
            }
        }
        socket.close();
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s