前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >NIO系列(五)——Udp协议(DatagramChannel)

NIO系列(五)——Udp协议(DatagramChannel)

作者头像
逝兮诚
发布2019-10-30 13:40:09
8050
发布2019-10-30 13:40:09
举报
文章被收录于专栏:代码人生代码人生

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/luo4105/article/details/73650509

DatagramChannel

DatagramChannel是收发UDP包的通道,与TCP协议不同,UDP发送不进行连接,也不对确认数据是否收到。

打开DatagramChannel

DatagramChannel server = DatagramChannel.open();
server.socket().bind(newInetSocketAddress(10086));

此例子是打开10086端口接收udp数据包

接收数据

通过receive()接收udp包

ByteBuffer receiveBuffer = ByteBuffer.allocate(64);
receiveBuffer.clear();
SocketAddress receiveAddr = server.receive(receiveBuffer);

SocketAddress可以获得发包的ip、端口等信息,用toString查看,格式如下

/127.0.0.1:57126

发送数据

通过send()发送udp包

DatagramChannel server = DatagramChannel.open();
ByteBuffer sendBuffer = ByteBuffer.wrap("client send".getBytes());
server.send(sendBuffer, new InetSocketAddress("127.0.0.1",10086));

连接

udp不存在真正意义上的连接,这里的连接是向特定服务地址用read和write接收发送数据包。

client.connect(new InetSocketAddress("127.0.0.1",10086));
int readSize= client.read(sendBuffer);
server.write(sendBuffer);

read()和write()只有在connect()后才能使用,不然会抛NotYetConnectedException异常。用read()接收时,如果没有接收到包,会抛PortUnreachableException异常。

例子

客户端发送,服务端接收的例子

/**
 * 发包的datagram
 *
 * @throws IOException
 * @throws InterruptedException
 */
@Test
public voidsendDatagram() throwsIOException, InterruptedException {
    DatagramChannelsendChannel= DatagramChannel.open();
    InetSocketAddresssendAddress= newInetSocketAddress("127.0.0.1", 9999);
    while (true) {
       sendChannel.send(ByteBuffer.wrap("发包".getBytes("UTF-8")), sendAddress);
       System.out.println("发包端发包");
       Thread.sleep(1000);
    }
}
 
/**
 * 收包端
 *
 * @throws IOException
 */
@Test
public voidreceive() throwsIOException {
    DatagramChannelreceiveChannel= DatagramChannel.open();
    InetSocketAddressreceiveAddress= newInetSocketAddress(9999);
    receiveChannel.bind(receiveAddress);
    ByteBufferreceiveBuffer= ByteBuffer.allocate(512);
    while (true) {
       receiveBuffer.clear();
       SocketAddresssendAddress= receiveChannel.receive(receiveBuffer);
       receiveBuffer.flip();
       System.out.print(sendAddress.toString() + " ");
       System.out.println(Charset.forName("UTF-8").decode(receiveBuffer));
    }
}
 
/**
 * 只接收和发送9999的数据包
 *
 * @throws IOException
 */
@Test
public voidtestConect1() throwsIOException {
    DatagramChannelconnChannel= DatagramChannel.open();
    connChannel.bind(newInetSocketAddress(9998));
    connChannel.connect(new InetSocketAddress("127.0.0.1",9999));
    connChannel.write(ByteBuffer.wrap("发包".getBytes("UTF-8")));
    ByteBufferreadBuffer= ByteBuffer.allocate(512);
    while (true) {
       try {
           readBuffer.clear();
           connChannel.read(readBuffer);
           readBuffer.flip();
           System.out.println(Charset.forName("UTF-8").decode(readBuffer));
       }catch(Exception e) {
 
       }
    }
}
 
/**
 * 只接收和发送9998的数据包
 *
 * @throws IOException
 */
@Test
public voidtestConect2() throwsIOException {
    DatagramChannelconnChannel= DatagramChannel.open();
    connChannel.bind(newInetSocketAddress(9999));
    connChannel.connect(new InetSocketAddress("127.0.0.1",9998));
    while (true) {
       connChannel.write(ByteBuffer.wrap("发包".getBytes("UTF-8")));
       System.out.println("发包成功");
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-06-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • DatagramChannel
    • 打开DatagramChannel
      • 接收数据
        • 发送数据
          • 连接
            • 例子
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档