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();