Java 杂谈java

第八节 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 
}
  1. ServerSocketChannel 创建:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

  1. ServerSocketChannel 关闭

serverSocketChannel.close();

  1. 绑定监听端口号:

serverSocketChannel.socket().bind(new InetSocketAddress(9999));

  1. 获取客户端的socket连接

SocketChannel socketChannel = serverSocketChannel.accept();

  1. 非阻塞模式

serverSocketChannel.configureBlocking(false);

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。 而是用来发送和接收数据包。

  1. 创建udp通道,并绑定端口号

DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));

  1. 接收数据包
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
//receive方法能够将接受的数据写入buf中
channel.receive(buf);
  1. 发送数据包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));

补充:DatagramChannel也可以使用connect方法和指定地址建立连接,然后像操作socketchannel一样使用 write和read方法。但是本质上仍然是无连接的udp协议

channel.connect(new InetSocketAddress("xxx", 80));   
int bytesRead = channel.read(buf);   
int bytesWritten = channel.write(buf);
上一篇 下一篇

猜你喜欢

热点阅读