分享

Java nio入门教程详解(二十七)

 360lec 2016-09-30

3.5.4 DatagramChannel

最后一个socket通道是DatagramChannel。正如SocketChannel对应SocketServerSocketChannel对应ServerSocket,每一个DatagramChannel对象也有一个关联的DatagramSocket对象。不过原命名模式在此并未适用:「DatagramSocketChannel」显得有点笨拙,因此采用了简洁的「DatagramChannel」名称。

正如SocketChannel模拟连接导向的流协议(如 TCP/IP),DatagramChannel则模拟包导向的无连接协议(如 UDP/IP):

  1. public abstract class DatagramChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel {
  2.     // 这里仅列出部分API
  3.     public static DatagramChannel open() throws IOException
  4.     public abstract DatagramSocket socket();
  5.     public abstract DatagramChannel connect(SocketAddress remote) throws IOException;
  6.     public abstract boolean isConnected();
  7.     public abstract DatagramChannel disconnect() throws IOException;
  8.     public abstract SocketAddress receive(ByteBuffer dst) throws IOException;
  9.     public abstract int send(ByteBuffer src, SocketAddress target)
  10.     public abstract int read(ByteBuffer dst) throws IOException;
  11.     public abstract long read(ByteBuffer[] dsts) throws IOException;
  12.     public abstract long read(ByteBuffer[] dsts, int offset, int length) throws IOException;
  13.     public abstract int write(ByteBuffer src) throws IOException;
  14.     public abstract long write(ByteBuffer[] srcs) throws IOException;
  15.     public abstract long write(ByteBuffer[] srcs, int offset, int length) throws IOException;
  16. }

创建DatagramChannel的模式和创建其他socket通道是一样的:调用静态的open()方法来创建一个新实例。新DatagramChannel会有一个可以通过调用socket()方法获取的对等DatagramSocket对象。DatagramChannel对象既可以充当服务器(监听者)也可以充当客户端(发送者)。如果您希望新创建的通道负责监听,那么通道必须首先被绑定到一个端口或地址/端口组合上。绑定DatagramChannel同绑定一个常规的DatagramSocket没什么区别,都是委托对等socket对象上的API实现的:

  1. DatagramChannel channel = DatagramChannel.open();
  2. DatagramSocket socket = channel.socket();
  3. socket.bind(new InetSocketAddress(portNumber));

DatagramChannel是无连接的。每个数据报(datagram)都是一个自包含的实体,拥有它自己的目的地址及不依赖其他数据报的数据净荷。与面向流的的socket不同,DatagramChannel可以发送单独的数据报给不同的目的地址。同样,DatagramChannel对象也可以接收来自任意地址的数据包。每个到达的数据报都含有关于它来自何处的信息(源地址)。

一个未绑定的DatagramChannel仍能接收数据包。当一个底层socket被创建时,一个动态生成的端口号就会分配给它。绑定行为要求通道关联的端口被设置为一个特定的值(此过程可能涉及安全检查或其他验证)。不论通道是否绑定,所有发送的包都含有DatagramChannel的源地址(带端口号)。未绑定的DatagramChannel可以接收发送给它的端口的包,通常是来回应该通道之前发出的一个包。已绑定的通道接收发送给它们所绑定的熟知端口(wellknown port)的包。数据的实际发送或接收是通过send()receive()方法来实现的:

  1. public abstract class DatagramChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel {
  2.     // 这里仅列出部分API
  3.     public abstract SocketAddress receive(ByteBuffer dst) throws IOException;
  4.     public abstract int send(ByteBuffer src, SocketAddress target)
  5. }

receive()方法将下次将传入的数据报的数据净荷复制到预备好的ByteBuffer中并返回一个SocketAddress对象以指出数据来源。如果通道处于阻塞模式,receive()可能无限期地休眠直到有包到达。如果是非阻塞模式,当没有可接收的包时则会返回null。如果包内的数据超出缓冲区能承受的范围,多出的数据都会被悄悄地丢弃。

假如您提供的ByteBuffer没有足够的剩余空间来存放您正在接收的数据包,没有被填充的字节都会被悄悄地丢弃。

调用send()会发送给定ByteBuffer对象的内容到给定SocketAddress对象所描述的目的地址和端口,内容范围为从当前position开始到末尾处结束。如果DatagramChannel对象处于阻塞模式,调用线程可能会休眠直到数据报被加入传输队列。如果通道是非阻塞的,返回值要么是字节缓冲区的字节数,要么是「0」。发送数据报是一个全有或全无(all-or-nothing)的行为。如果传输队列没有足够空间来承载整个数据报,那么什么内容都不会被发送。

如果安装了安全管理器,那么每次调用send()receive()时安全管理器的checkConnect()方法都会被调用以验证目的地址,除非通道处于已连接的状态(本节后面会讨论到)。

请注意,数据报协议的不可靠性是固有的,它们不对数据传输做保证。send()方法返回的非零值并不表示数据报到达了目的地,仅代表数据报被成功加到本地网络层的传输队列。此外,传输过程中的协议可能将数据报分解成碎片。例如,以太网不能传输超过1,500个字节左右的包。如果您的数据报比较大,那么就会存在被分解成碎片的风险,成倍地增加了传输过程中包丢失的几率。被分解的数据报在目的地会被重新组合起来,接收者将看不到碎片。但是,如果有一个碎片不能按时到达,那么整个数据报将被丢弃。

DatagramChannel有一个connect()方法:

  1. public abstract class DatagramChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel {
  2.     // 这里仅列出部分API
  3.     public abstract DatagramChannel connect(SocketAddress remote) throws IOException;
  4.     public abstract boolean isConnected();
  5.     public abstract DatagramChannel disconnect() throws IOException;
  6. }

DatagramChannel对数据报socket的连接语义不同于对流socket的连接语义。有时候,将数据报对话限制为两方是很可取的。将DatagramChannel置于已连接的状态可以使除了它所「连接」到的地址之外的任何其他源地址的数据报被忽略。这是很有帮助的,因为不想要的包都已经被网络层丢弃了,从而避免了使用代码来接收、检查然后丢弃包的麻烦。

DatagramChannel已连接时,使用同样的令牌,您不可以发送包到除了指定给connect()方法的目的地址以外的任何其他地址。试图一定要这样做的话会导致一个SecurityException异常。

我们可以通过调用带SocketAddress对象的connect()方法来连接一个DatagramChannel,该SocketAddress对象描述了DatagramChannel远程对等体的地址。如果已经安装了一个安全管理器,那么它会进行权限检查。之后,每次send/receive时就不会再有安全检查了,因为来自或去到任何其他地址的包都是不允许的。

已连接通道会发挥作用的使用场景之一是一个客户端/服务器模式、使用UDP通讯协议的实时游戏。每个客户端都只和同一台服务器进行会话而希望忽视任何其他来源地数据包。将客户端的DatagramChannel实例置于已连接状态可以减少按包计算的总开销(因为不需要对每个包进行安全检查)和剔除来自欺骗玩家的假包。服务器可能也想要这样做,不过需要每个客户端都有一个DatagramChannel对象。

不同于流socket,数据报socket的无状态性质不需要同远程系统进行对话来建立连接状态。没有实际的连接,只有用来指定允许的远程地址的本地状态信息。由于此原因,DatagramChannel上也就没有单独的finishConnect()方法。我们可以使用isConnected()方法来测试一个数据报通道的连接状态。

不同于SocketChannel(必须连接了才有用并且只能连接一次),DatagramChannel对象可以任意次数地进行连接或断开连接。每次连接都可以到一个不同的远程地址。调用disconnect()方法可以配置通道,以便它能再次接收来自安全管理器(如果已安装)所允许的任意远程地址的数据或发送数据到这些地址上。

当一个DatagramChannel处于已连接状态时,发送数据将不用提供目的地址而且接收时的源地址也是已知的。这意味着DatagramChannel已连接时可以使用常规的read()write()方法,包括scatter/gather形式的读写来组合或分拆包的数据:

  1. public abstract class DatagramChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel {
  2.     // 这里仅列出部分API
  3.     public abstract int read(ByteBuffer dst) throws IOException;
  4.     public abstract long read(ByteBuffer[] dsts) throws IOException;
  5.     public abstract long read(ByteBuffer[] dsts, int offset, int length) throws IOException;
  6.     public abstract int write(ByteBuffer src) throws IOException;
  7.     public abstract long write(ByteBuffer[] srcs) throws IOException;
  8.     public abstract long write(ByteBuffer[] srcs, int offset, int length) throws IOException;
  9. }

read()方法返回读取字节的数量,如果通道处于非阻塞模式的话这个返回值可能是「0」。write()方法的返回值同send()方法一致:要么返回您的缓冲区中的字节数量,要么返回「0」(如果由于通道处于非阻塞模式而导致数据报不能被发送)。当通道不是已连接状态时调用read()write()方法,都将产生NotYetConnectedException异常。

数据报通道不同于流socket。由于它们的有序而可靠的数据传输特性,流socket非常得有用。大多数网络连接都是流 socket(TCP/IP 就是一个显著的例子)。但是,像 TCP/IP 这样面向流的的协议为了在包导向的互联网基础设施上维护流语义必然会产生巨大的开销,并且流隐喻不能适用所有的情形。数据报的吞吐量要比流协议高很多,并且数据报可以做很多流无法完成的事情。

下面列出了一些选择数据报socket而非流socket的理由:

  • 您的程序可以承受数据丢失或无序的数据。
  • 您希望「发射后不管」(fire and forget)而不需要知道您发送的包是否已接收。
  • 数据吞吐量比可靠性更重要。
  • 您需要同时发送数据给多个接受者(多播或者广播)。
  • 包隐喻比流隐喻更适合手边的任务。

如果以上特征中的一个或多个适用于您的程序,那么数据报设计对您来说就是合适的。

例 3-9 显示了如何使用DatagramChannel发送请求到多个地址上的时间服务器。DatagramChannel接着会等待回复(reply)的到达。对于每个返回的回复,远程时间会同本地时间进行比较。由于数据报传输不保证一定成功,有些回复可能永远不会到达。大多数Linux和Unix系统都默认提供时间服务。互联网上也有一个公共时间服务器,如time.nist.gov。防火墙或者您的ISP可能会干扰数据报传输,这是因人而异的。

  1. /*
  2.  *例 3-9 使用DatagramChannel的时间服务客户端
  3.  */
  4. package com.ronsoft.books.nio.channels;
  5. import java.nio.ByteBuffer;
  6. import java.nio.ByteOrder;
  7. import java.nio.channels.DatagramChannel;
  8. import java.net.InetSocketAddress;
  9. import java.util.Date;
  10. import java.util.List;
  11. import java.util.LinkedList;
  12. import java.util.Iterator;
  13. /**
  14. * Request time service, per RFC 868. RFC 868
  15. * (http://www./rfc/rfc0868.txt) is a very simple time protocol
  16. * whereby one system can request the current time from another system.
  17. * Most Linux, BSD and Solaris systems provide RFC 868 time service
  18. * on port 37. This simple program will inter-operate with those.
  19. * The National Institute of Standards and Technology (NIST) operates
  20. * a public time server at time.nist.gov.
  21. *
  22. * The RFC 868 protocol specifies a 32 bit unsigned value be sent,
  23. * representing the number of seconds since Jan 1, 1900. The Java
  24. * epoch begins on Jan 1, 1970 (same as unix) so an adjustment is
  25. * made by adding or subtracting 2,208,988,800 as appropriate. To
  26. * avoid shifting and masking, a four-byte slice of an
  27. * eight-byte buffer is used to send/recieve. But getLong()
  28. * is done on the full eight bytes to get a long value.
  29. *
  30. * When run, this program will issue time requests to each hostname
  31. * given on the command line, then enter a loop to receive packets.
  32. * Note that some requests or replies may be lost, which means
  33. * this code could block forever.
  34. *
  35. * @author Ron Hitchens (ron@ronsoft.com)
  36. */
  37. public class TimeClient {
  38.     private static final int DEFAULT_TIME_PORT = 37;
  39.     private static final long DIFF_1900 = 2208988800L;
  40.     protected int port = DEFAULT_TIME_PORT;
  41.     protected List remoteHosts;
  42.     protected DatagramChannel channel;
  43.    
  44.     public TimeClient (String [] argv) throws Exception
  45.         if (argv.length == 0) {
  46.             throw new Exception ("Usage: [ -p port ] host ...");
  47.         }
  48.         parseArgs(argv);
  49.         this.channel = DatagramChannel.open();
  50.     }
  51.    
  52.     protected InetSocketAddress receivePacket (DatagramChannel channel, ByteBuffer buffer) throws Exception {
  53.         buffer.clear();
  54.         // Receive an unsigned 32-bit, big-endian value
  55.         return ((InetSocketAddress) channel.receive (buffer));
  56.     }
  57.    
  58.     // Send time requests to all the supplied hosts
  59.     protected void sendRequests() throws Exception {
  60.         ByteBuffer buffer = ByteBuffer.allocate (1);
  61.         Iterator it = remoteHosts.iterator();
  62.         while (it.hasNext()) {
  63.             InetSocketAddress sa = (InetSocketAddress) it.next();
  64.             System.out.println ("Requesting time from " + sa.getHostName() + ":" + sa.getPort());
  65.             // Make it empty (see RFC868)
  66.             buffer.clear().flip();
  67.             // Fire and forget
  68.             channel.send (buffer, sa);
  69.         }
  70.     }
  71.    
  72.     // Receive any replies that arrive
  73.     public void getReplies() throws Exception {
  74.         // Allocate a buffer to hold a long value
  75.         ByteBuffer longBuffer = ByteBuffer.allocate (8);
  76.         // Assure big-endian (network) byte order
  77.         longBuffer.order (ByteOrder.BIG_ENDIAN);
  78.         // Zero the whole buffer to be sure
  79.         longBuffer.putLong (0, 0);
  80.         // Position to first byte of the low-order 32 bits
  81.         longBuffer.position (4);
  82.         // Slice the buffer; gives view of the low-order 32 bits
  83.         ByteBuffer buffer = longBuffer.slice();
  84.         int expect = remoteHosts.size();
  85.         int replies = 0;
  86.         System.out.println ("");
  87.         System.out.println ("Waiting for replies...");
  88.         while (true) {
  89.             InetSocketAddress sa = receivePacket(channel, buffer);
  90.             buffer.flip();
  91.             replies++;
  92.             printTime(longBuffer.getLong(0), sa);
  93.             if (replies == expect) {
  94.                 System.out.println ("All packets answered");
  95.                 break;
  96.             }
  97.             // Some replies haven't shown up yet
  98.             System.out.println ("Received " + replies + " of " + expect + " replies");
  99.         }
  100.     }
  101.    
  102.     // Print info about a received time reply
  103.     protected void printTime (long remote1900, InetSocketAddress sa) {
  104.         // local time as seconds since Jan 1, 1970
  105.         long local = System.currentTimeMillis() / 1000;
  106.         // remote time as seconds since Jan 1, 1970
  107.         long remote = remote1900 - DIFF_1900;
  108.         Date remoteDate = new Date (remote * 1000);
  109.         Date localDate = new Date (local * 1000);
  110.         long skew = remote - local;
  111.         System.out.println ("Reply from " + sa.getHostName() + ":" + sa.getPort());
  112.         System.out.println (" there: " + remoteDate);
  113.         System.out.println (" here: " + localDate);
  114.         System.out.print (" skew: ");
  115.         if (skew == 0) {
  116.             System.out.println ("none");
  117.         } else if (skew > 0) {
  118.             System.out.println (skew + " seconds ahead");
  119.         } else {
  120.             System.out.println ((-skew) + " seconds behind");
  121.         }
  122.     }
  123.    
  124.     protected void parseArgs (String [] argv) {
  125.         remoteHosts = new LinkedList();
  126.         for (int i = 0; i < argv.length; i++) {
  127.             String arg = argv [i];
  128.             // Send client requests to the given port
  129.             if (arg.equals("-p")) {
  130.                 i++;
  131.                 this.port = Integer.parseInt (argv [i]);
  132.                 continue;
  133.             }
  134.             // Create an address object for the hostname
  135.             InetSocketAddress sa = new InetSocketAddress(arg, port);
  136.             // Validate that it has an address
  137.             if (sa.getAddress() == null) {
  138.                 System.out.println ("Cannot resolve address: " + arg);
  139.                 continue;
  140.             }
  141.             remoteHosts.add(sa);
  142.         }
  143.     }
  144.    
  145.     // --------------------------------------------------------------
  146.     public static void main (String [] argv) throws Exception {
  147.         TimeClient client = new TimeClient(argv);
  148.         client.sendRequests();
  149.         client.getReplies();
  150.     }
  151. }

例 3-10 中的程序是一个RFC 868时间服务器。这段代码回答来自例 3-9 中的客户端的请求并显示出DatagramChannel是怎样绑定到一个熟知端口然后开始监听来自客户端的请求的。该时间服务器仅监听数据报(UDP)请求。大多数Unix和Linux系统提供的rdate命令使用TCP协议连接到一个RFC 868时间服务。

  1. /*
  2.  *例 3-10 DatagramChannel 时间服务器
  3.  */
  4. package com.ronsoft.books.nio.channels;
  5. import java.nio.ByteBuffer;
  6. import java.nio.ByteOrder;
  7. import java.nio.channels.DatagramChannel;
  8. import java.net.SocketAddress;
  9. import java.net.InetSocketAddress;
  10. import java.net.SocketException;
  11. /**
  12. * Provide RFC 868 time service (http://www./rfc/rfc0868.txt).
  13. * This code implements an RFC 868 listener to provide time
  14. * service. The defined port for time service is 37. On most
  15. * unix systems, root privilege is required to bind to ports
  16. * below 1024. You can either run this code as root or
  17. * provide another port number on the command line. Use
  18. * "-p port#" with TimeClient if you choose an alternate port.
  19. *
  20. * Note: The familiar rdate command on unix will probably not work
  21. * with this server. Most versions of rdate use TCP rather than UDP
  22. * to request the time.
  23. *
  24. * @author Ron Hitchens (ron@ronsoft.com)
  25. */
  26. public class TimeServer {
  27.     private static final int DEFAULT_TIME_PORT = 37;
  28.     private static final long DIFF_1900 = 2208988800L;
  29.     protected DatagramChannel channel;
  30.    
  31.     public TimeServer (int port) throws Exception {
  32.         this.channel = DatagramChannel.open();
  33.         this.channel.socket().bind (new InetSocketAddress (port));
  34.         System.out.println ("Listening on port " + port + " for time requests");
  35.     }
  36.    
  37.     public void listen() throws Exception {
  38.         // Allocate a buffer to hold a long value
  39.         ByteBuffer longBuffer = ByteBuffer.allocate (8);
  40.         // Assure big-endian (network) byte order
  41.         longBuffer.order (ByteOrder.BIG_ENDIAN);
  42.         // Zero the whole buffer to be sure
  43.         longBuffer.putLong (0, 0);
  44.         // Position to first byte of the low-order 32 bits
  45.         longBuffer.position (4);
  46.         // Slice the buffer; gives view of the low-order 32 bits
  47.         ByteBuffer buffer = longBuffer.slice();
  48.         while (true) {
  49.             buffer.clear();
  50.             SocketAddress sa = this.channel.receive (buffer);
  51.             if (sa == null) {
  52.                 continue; // defensive programming
  53.             }
  54.             // Ignore content of received datagram per RFC 868
  55.             System.out.println ("Time request from " + sa);
  56.             buffer.clear(); // sets pos/limit correctly
  57.             // Set 64-bit value; slice buffer sees low 32 bits
  58.             longBuffer.putLong (0, (System.currentTimeMillis() / 1000) + DIFF_1900);
  59.             this.channel.send (buffer, sa);
  60.         }
  61.     }
  62.    
  63.     // --------------------------------------------------------------
  64.     public static void main (String [] argv) throws Exception {
  65.         int port = DEFAULT_TIME_PORT;
  66.         if (argv.length > 0) {
  67.             port = Integer.parseInt (argv [0]);
  68.         }
  69.         try {
  70.             TimeServer server = new TimeServer (port);
  71.             server.listen();
  72.         } catch (SocketException e) {
  73.             System.out.println ("Can't bind to port " + port + ", try a different one");
  74.         }
  75.     }
  76. }

Java nio入门教程详解(二十八)

2 0
我们认为:用户的主要目的,是为了获取有用的信息,而不是来点击广告的。因此本站将竭力做好内容,并将广告和内容进行分离,确保所有广告不会影响到用户的正常阅读体验。用户仅凭个人意愿和兴趣爱好点击广告。
我们坚信:只有给用户带来价值,用户才会给我们以回报。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多