Java Tutorial/Network/DatagramChannel

Материал из Java эксперт
Перейти к: навигация, поиск

Set up DatagramChannel

   <source lang="java">

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);
     }
   }
 }

}</source>





Socket based on new IO and DatagramChannel

   <source lang="java">

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; import java.util.Date; public class MainClass {

 public static void main(String[] args) throws IOException {
   DatagramChannel channel = DatagramChannel.open();
   SocketAddress address = new InetSocketAddress(0);
   DatagramSocket socket = channel.socket();
   socket.bind(address);
   SocketAddress server = new InetSocketAddress("time-a.nist.gov", 37);
   channel.connect(server);
   ByteBuffer buffer = ByteBuffer.allocate(8);
   buffer.order(ByteOrder.BIG_ENDIAN);
   // send a byte of data to the server
   buffer.put((byte) 0);
   buffer.flip();
   channel.write(buffer);
   // get the buffer ready to receive data
   buffer.clear();
   // fill the first four bytes with zeros
   buffer.putInt(0);
   channel.read(buffer);
   buffer.flip();
   // convert seconds since 1900 to a java.util.Date
   long secondsSince1900 = buffer.getLong();
   long differenceBetweenEpochs = 2208988800L;
   long secondsSince1970 = secondsSince1900 - differenceBetweenEpochs;
   long msSince1970 = secondsSince1970 * 1000;
   Date time = new Date(msSince1970);
   System.out.println(time);
 }

}</source>