NIOServer
package com.ctgu.nio.socket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
public class NIOServer {
public static void main(String[] args) throws Exception {
//1.create a serverSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//2.create a selector
Selector selector = Selector.open();
//3.通道绑定端口
serverSocketChannel.bind(new InetSocketAddress(9999));
//4.设置非阻塞
serverSocketChannel.configureBlocking(false);
//5.serverSocketChannel注册
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
// 6.1 监控客户端
if (selector.select(2000) == 0) {
System.out.println("Server:没有客户端搭理我,我就干点别的事");
continue;
}
// 6.2 得到SelectionKey,判断通道里的事件
Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if (key.isAcceptable()) {
System.out.println("接收到客户端连接");
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector,
SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}
if (key.isReadable()) {
SocketChannel channel = (SocketChannel) key.channel();
channel.configureBlocking(false);
ByteBuffer buffer = (ByteBuffer) key.attachment();
channel.read(buffer);
System.out.println("客户端发来数据:" + new String(buffer.array()));
}
keyIterator.remove();
}
}
}
}
NIOClient
package com.ctgu.nio.socket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class NIOClient {
public static void main(String[] args) throws Exception{
//1.得到一个网络通道
SocketChannel channel = SocketChannel.open();
//2.设置非阻塞方式
channel.configureBlocking(false);
//3.提供服务器端的IP地址和端口号
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9999);
//4.连接服务器端
if(!channel.connect(address)) {
while (!channel.finishConnect()) {
System.out.println("Client:连接服务器端的同时,我还可以做点别的事");
}
}
//5.得到一个缓冲区并存入数据
String msg = "hello,NIOServer";
ByteBuffer writeBuf = ByteBuffer.wrap(msg.getBytes());
//6.发送数据
channel.write(writeBuf);
System.in.read();
}
}
网友评论