zoukankan      html  css  js  c++  java
  • Java NIO DatagramChannel

    A Java NIO DatagramChannel is a channel that can send and receive UDP packets. Since UDP is a connection-less network protocol, you cannot just by default read and write to a DatagramChannel like you do from other channels. Instead you send and receive packets of data.

    Opening a DatagramChannel

    Here is how you open a DatagramChannel:

    DatagramChannel channel = DatagramChannel.open();
    channel.socket().bind(new InetSocketAddress(9999));

    This example opens a DatagramChannel which can receive packets on UDP port 9999.

    Receiving Data

    You receive data from a DatagramChannel by calling its receive() method, like this:

    ByteBuffer buf = ByteBuffer.allocate(48);
    buf.clear();
    
    channel.receive(buf);

    The receive() method will copy the content of a received packet of data into the given Buffer. If the received packet contains more data than the Buffer can contain, the remaining data is discarded silently.

    Sending Data

    You can send data via a DatagramChannel by calling its send() method, like this:

    String newData = "New String to write to file..."
                        + System.currentTimeMillis();
        
    ByteBuffer buf = ByteBuffer.allocate(48);
    buf.clear();
    buf.put(newData.getBytes());
    buf.flip();
    
    int bytesSent = channel.send(buf, new InetSocketAddress("jenkov.com", 80));

    This example sends the string to the "jenkov.com" server on UDP port 80. Nothing is listening on that port though, so nothing will happen. You will not be notified of whether the send packet was received or not, since UDP does not make any guarantees about delivery of data.

    Connecting to a Specific Address

    It is possible to "connect" a DatagramChannel to a specific address on the network. Since UDP is connection-less, this way of connecting to an address does not create a real connection, like with a TCP channel. Rather, it locks your DatagramChannel so you can only send and receive data packets from one specific address.

    Here is an example:

    channel.connect(new InetSocketAddress("jenkov.com", 80));   

    When connected you can also use the read() and write() method, as if you were using a traditional channel. You just don't have any guarantees about delivery of the sent data. Here are a few examples:

    int bytesRead = channel.read(buf);   
    int bytesWritten = channel.write(buf);

     Ref:

    http://tutorials.jenkov.com/java-nio/datagram-channel.html

  • 相关阅读:
    《JavaScript & jQuery交互式Web前端开发》之JavaScript基础指令
    hash_map原理及C++实现
    开源大数据引擎:Greenplum 数据库架构分析
    摆脱命令行,Ubuntu下配置Android开发环境
    JS学习十四天----server端运行JS代码
    【苦读官方文档】2.Android应用程序基本原理概述
    UVA
    android页面间传递对象
    大话设计模式C++版——建造者模式
    poj 3370 Halloween treats
  • 原文地址:https://www.cnblogs.com/winner-0715/p/8544914.html
Copyright © 2011-2022 走看看