ServerSocketChannel
ServerSocketChannel是一個(gè)用于監(jiān)聽傳入TCP連接的channel,就像標(biāo)準(zhǔn)Java網(wǎng)絡(luò)中的ServerSocket一樣。
java bio中的serversocket和nio中的socket有些類似,兩者使用可參考如下:
BIO模式
ServerSocket ss = new ServerSocket(10086);
System.out.println("服務(wù)器正常啟動(dòng)。。。");
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 創(chuàng)建:
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
- ServerSocketChannel 關(guān)閉
serverSocketChannel.close();
- 綁定監(jiān)聽端口號(hào):
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
- 獲取客戶端的socket連接
SocketChannel socketChannel = serverSocketChannel.accept();
- 非阻塞模式
serverSocketChannel.configureBlocking(false);
- 注意:非阻塞模式下accept方法會(huì)立刻返回客戶端的socket連接,如果沒(méi)有則返回為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是可以發(fā)送和接收UDP數(shù)據(jù)包的通道。 由于UDP是一種無(wú)連接的網(wǎng)絡(luò)協(xié)議,因此無(wú)法像在其他通道中那樣默認(rèn)讀取和寫入DatagramChannel。 而是用來(lái)發(fā)送和接收數(shù)據(jù)包。
- 創(chuàng)建udp通道,并綁定端口號(hào)
DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));
- 接收數(shù)據(jù)包
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
//receive方法能夠?qū)⒔邮艿臄?shù)據(jù)寫入buf中
channel.receive(buf);
- 發(fā)送數(shù)據(jù)包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));
- 需要注意的: 字符串發(fā)送到UDP端口80上的“xxx.com”服務(wù)器。但是如果沒(méi)有任何服務(wù)偵聽該端口,發(fā)送端也不會(huì)收到任何響應(yīng)。因?yàn)閁DP是無(wú)連接的不保證數(shù)據(jù)發(fā)送是否成功。
補(bǔ)充:DatagramChannel也可以使用connect方法和指定地址建立連接,然后像操作socketchannel一樣使用 write和read方法。但是本質(zhì)上仍然是無(wú)連接的udp協(xié)議
channel.connect(new InetSocketAddress("xxx", 80));
int bytesRead = channel.read(buf);
int bytesWritten = channel.write(buf);