DatagramChannel
In this chapter you will learn:
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;
//from ja v a 2 s .c o m
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 Time Client
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;
//from j a v a2 s.c o m
public class UDPTimeClient {
public static void main(String[] args) throws Exception {
DatagramChannel channel = DatagramChannel.open();
// port 0 selects any available port
SocketAddress address = new InetSocketAddress(0);
DatagramSocket socket = channel.socket();
socket.setSoTimeout(5000);
socket.bind(address);
SocketAddress server = new InetSocketAddress("time.nist.gov", 37);
ByteBuffer buffer = ByteBuffer.allocate(8192);
// time protocol always uses big-endian order
buffer.order(ByteOrder.BIG_ENDIAN);
// Must put at least one byte of data in the buffer;
// it doesn't matter what it is.
buffer.put((byte) 65);
buffer.flip();
channel.send(buffer, server);
buffer.clear();
buffer.put((byte) 0).put((byte) 0).put((byte) 0).put((byte) 0);
channel.receive(buffer);
buffer.flip();
long secondsSince1970 = buffer.getLong();
System.out.println(secondsSince1970);
channel.close();
}
}
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;
// j av a 2s . com
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);
}
}
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Socket