栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

原生JAVA-nio udp demo

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

原生JAVA-nio udp demo

package com.iphanta.service;


import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.StandardCharsets;


public class DatagramSocketChannelDemo {

    public static void main(String[] args) throws Exception {
        startServer(10086);
    }

    //启动udp 服务端
    public static void startServer(int port) throws Exception{
        DatagramChannel open = DatagramChannel.open();
        open.socket().bind(new InetSocketAddress(port));
        System.err.println("udp server start port:" + port);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //收消息
        while (true) {
            buffer.clear();
            System.err.println("接受消息中..");
            SocketAddress socketAddress = open.receive(buffer);
            buffer.flip();
            System.err.println(socketAddress);
            System.out.println(StandardCharsets.UTF_8.decode(buffer));
        }
    }

    //udp 发消息
    public static void send() throws Exception{
        DatagramChannel open = DatagramChannel.open();
        //发消息
        open.send(ByteBuffer.wrap("hello".getBytes()), new InetSocketAddress("127.0.0.1", 10086));
        System.err.println("发送完成");
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/328466.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号