nio(四)--socket与channel

NetWorkChannel:

 SelectorProvider provider=SelectorProvider.provider();
        NetworkChannel socketChannel=provider.openSocketChannel();
        SocketAddress address=new InetSocketAddress(3080);
        Set<SocketOption<?>> socketOptions=socketChannel.supportedOptions();
        System.out.println(socketOptions.toString());

        socketChannel.setOption(StandardSocketOptions.IP_TOS,3);
        boolean b=socketChannel.getOption(StandardSocketOptions.SO_KEEPALIVE);

MulticastChannel:

服务端:
 long t=1;

        DatagramChannel dc=DatagramChannel.open(StandardProtocolFamily.INET);
        dc.bind(null);
        InetAddress group=InetAddress.getByName("224.0.0.5");
        int port=9000;
        while (true){
            Thread.sleep(1000);
            dc.send(ByteBuffer.wrap(("广播电视"+t++).getBytes()),new InetSocketAddress(group,port));
        }
客户端:

        NetworkInterface networkInterface=NetworkInterface.getByName("lo");//选择网络接口
        DatagramChannel dc=DatagramChannel.open(StandardProtocolFamily.INET);//打开数据包通道

        dc.setOption(StandardSocketOptions.SO_REUSEADDR,true);//设置数据包通道
        dc.bind(new InetSocketAddress(9000));//设置数据包通道端口
        dc.setOption(StandardSocketOptions.IP_MULTICAST_IF,networkInterface);//绑定网络接口

        InetAddress group=InetAddress.getByName("224.0.0.5");
        MembershipKey key=dc.join(group,networkInterface);//加入多播组

        ByteBuffer buffer=ByteBuffer.allocate(1024);
        dc.receive(buffer);
        System.out.println(new String(buffer.array()));
        key.drop();
        dc.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值