第八节 netty前传-NIO 几种channel介绍02
2018-10-28 本文已影响3人
勃列日涅夫
ServerSocketChannel
ServerSocketChannel是一个用于监听传入TCP连接的channel,就像标准Java网络中的ServerSocket一样。
java bio中的serversocket和nio中的socket有些类似,两者使用可参考如下:
BIO模式
ServerSocket ss = new ServerSocket(10086);
System.out.println("服务器正常启动。。。");
while(true){
Socket socket = ss.accept();
System.out.println("用户接入成功。。。");
//do something
}
}
NIO模式
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
while(true){
SocketChannel socketChannel =
serverSocketChannel.accept();
//do something
}
- ServerSocketChannel 创建:
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
- ServerSocketChannel 关闭
serverSocketChannel.close();
- 绑定监听端口号:
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
- 获取客户端的socket连接
SocketChannel socketChannel = serverSocketChannel.accept();
- 非阻塞模式
serverSocketChannel.configureBlocking(false);
- 注意:非阻塞模式下accept方法会立刻返回客户端的socket连接,如果没有则返回为null
下面为基本的使用的代码怕片段:
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
serverSocketChannel.configureBlocking(false);、
//不断的去获取socket连接
while(true){
SocketChannel socketChannel =
serverSocketChannel.accept();
//或取到连接后做处理
if(socketChannel != null){
//do something with socketChannel...
}
}
UDPchannel,DatagramChannel
DatagramChannel是可以发送和接收UDP数据包的通道。 由于UDP是一种无连接的网络协议,因此无法像在其他通道中那样默认读取和写入DatagramChannel。 而是用来发送和接收数据包。
- 创建udp通道,并绑定端口号
DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));
- 接收数据包
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
//receive方法能够将接受的数据写入buf中
channel.receive(buf);
- 发送数据包send方法
String newData = "new data";
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
int bytesSent = channel.send(buf, new InetSocketAddress("xxx.com", 80));
- 需要注意的: 字符串发送到UDP端口80上的“xxx.com”服务器。但是如果没有任何服务侦听该端口,发送端也不会收到任何响应。因为UDP是无连接的不保证数据发送是否成功。
补充:DatagramChannel也可以使用connect方法和指定地址建立连接,然后像操作socketchannel一样使用 write和read方法。但是本质上仍然是无连接的udp协议
channel.connect(new InetSocketAddress("xxx", 80));
int bytesRead = channel.read(buf);
int bytesWritten = channel.write(buf);