Showing posts with label server. Show all posts
Showing posts with label server. Show all posts

Thursday, July 17, 2008

UDP Server Socket using Java

The following simple example shows how to open a UDP server socket using Java. The code receives strings from a UDP socket and print them in the standard output.
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.DatagramPacket;

public class SimpleUDPSSocket extends Thread
{
public SimpleUDPSSocket() throws Exception
{
_dSocket = new DatagramSocket(PORT);
_running = false;
}

public void run()
{
byte buf[] = new byte[MAX_SIZE];
DatagramPacket packet = new DatagramPacket (buf, buf.length);
String data;
_running = true;
while (_running) {
try {
_dSocket.receive (packet);
}
catch (Exception ex) {
_running = false;
break;
}
data = new String(packet.getData(), 0, packet.getLength());
System.out.println (data);
}
}

private DatagramSocket _dSocket;
private boolean _running;
private static final int PORT = 4444;
private static final int MAX_SIZE = 64;
}