NIO小练习,编写服务端和客户端
将服务端和客户端注册到selector,利用缓冲区进行数据的传输,
具体代码和注释如下:
服务端:
public class NioServer {
public static void main(String[] args) throws IOException {
//创建ServerSocketChannel
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
//得到一个selector对象
Selector selector = Selector.open();
//绑定端口
InetSocketAddress inetSocketAddress=new InetSocketAddress(8848);
serverSocketChannel.socket().bind(inetSocketAddress);
//设置为非阻塞
serverSocketChannel.configureBlocking(false);
//把serverSokcetChannel注册到selector 关心事件为OP_ACCPET,也就是连接事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//循环等待连接
while(true){
//先等待一秒钟 如果没有连接事件发生,则返回
if(selector.select(1000)==0){
System.out.println("等待了1秒 无事发生");
continue;
}
//如果返回大于0 则获得有事件发生的selectionKey
//通过selectionKey反向获取通道
Set<SelectionKey> selectionKeys=selector.selectedKeys();
//使用迭代器遍历Set集合
Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
while(selectionKeyIterator.hasNext()){
SelectionKey selectionKey=selectionKeyIterator.next();
//根据selectionKey的通道发生的事件进行处理
if(selectionKey.isAcceptable()){
//处理的是OP_ACCPET,也就是连接事件
//为该客户生成一个通道 socketChannel
SocketChannel socketChannel=serverSocketChannel.accept();
System.out.println("客户端连接成功");
//将该通道设置为非阻塞状态 否则会报java.nio.channels.IllegalBlockingModeException异常
socketChannel.configureBlocking(false);
//将当前通道注册到selector中,关注事件为OP_READ,并绑定一个buffer
socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}
else if(selectionKey.isReadable()){
//如果selectionKey是可读的
//反向获取通道
SocketChannel channel =(SocketChannel)selectionKey.channel();
//获取该通道绑定的buffer
ByteBuffer attachment = (ByteBuffer)selectionKey.attachment();
channel.read(attachment);
System.out.println("来自客户端的信息是"+new String(attachment.array()));
}
//从集合中删除key 防止重复操作
selectionKeyIterator.remove();
}
}
}
}
public class NioClient {
public static void main(String[] args) throws IOException {
//创建一个网络通道
SocketChannel socketChannel=SocketChannel.open();
//设置非阻塞
socketChannel.configureBlocking(false);
// 通过服务器ip和端口和服务器进行绑定
InetSocketAddress inetSocketAddress=new InetSocketAddress("127.0.0.1",8848);
if(!socketChannel.connect(inetSocketAddress)){
while (!socketChannel.finishConnect()){
System.out.println("非阻塞,可以做其他工作");
}
}
//连接成功 发送数据
String str="hello,server";
ByteBuffer wrap = ByteBuffer.wrap(str.getBytes());
//发送数据 将buffer中数据发送至通道
socketChannel.write(wrap);
System.in.read();
}
}
客户端:

浙公网安备 33010602011771号