Java Tutorial/Network/UDP Server
UDP Echo Server With Channels
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
public class MainClass {
public static void main(String[] args) throws Exception {
DatagramChannel channel = DatagramChannel.open();
DatagramSocket socket = channel.socket();
SocketAddress address = new InetSocketAddress(9999);
socket.bind(address);
ByteBuffer buffer = ByteBuffer.allocateDirect(65507);
while (true) {
SocketAddress client = channel.receive(buffer);
buffer.flip();
channel.send(buffer, client);
buffer.clear();
}
}
}
UDP pocket sender and receiver
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
class PacketReceiver {
public static void main(String[] args) throws Exception {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
DatagramSocket socket = new DatagramSocket(5002);
socket.receive(packet);
System.out.println(packet.getSocketAddress());
buffer = packet.getData();
System.out.println(new String(buffer));
}
}
class PacketSender {
public static void main(String[] args) throws Exception {
byte[] buffer = "data".getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, new InetSocketAddress(
"localhost", 5002));
DatagramSocket socket = new DatagramSocket(5003);
socket.send(packet);
}
}
UDP time server based on New IO
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.DatagramChannel;
public class UDPTimeServer {
public final static int DEFAULT_PORT = 37;
public static void main(String[] args) throws IOException {
int port = 37;
ByteBuffer in = ByteBuffer.allocate(8192);
ByteBuffer out = ByteBuffer.allocate(8);
out.order(ByteOrder.BIG_ENDIAN);
SocketAddress address = new InetSocketAddress(port);
DatagramChannel channel = DatagramChannel.open();
DatagramSocket socket = channel.socket();
socket.bind(address);
System.err.println("bound to " + address);
while (true) {
try {
in.clear();
SocketAddress client = channel.receive(in);
System.err.println(client);
long secondsSince1970 = System.currentTimeMillis();
out.clear();
out.putLong(secondsSince1970);
out.flip();
out.position(4);
channel.send(out, client);
} catch (Exception ex) {
System.err.println(ex);
}
}
}
}