NIO服务器和客户端通讯简单例子
废话不多说直接上代码。
首先是服务端代码:
package nio;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class NioServer {
public Selector selector;
//初始化服务器
public void initServer(int port) throws Exception{
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//非阻塞
serverSocketChannel.configureBlocking(false);
//绑定端口
serverSocketChannel.bind(new InetSocketAddress(port));
//获取一个通道管理器
selector = Selector.open();
//1.绑定通道管理器;
//2.当事件到达时,selector.seletor()会返回否则会一直阻塞,此时注册的是OP_ACCEPT事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
//监听事件并处理
public void listen() throws Exception{
while(true){
//当事件到达时,selector.seletor()会返回否则会一直阻塞
selector.select();
System.out.println("接收到了");
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
iterator.remove();
handle(selectionKey);
}
}
}
//处理
public void handle(SelectionKey selectionKey) throws Exception{
if(selectionKey.isAcceptable()){
handleaccept(selectionKey);
}else if(selectionKey.isReadable()){
handleread(selectionKey);
}
}
//如果接收到客户端请求则将该channel改成监听on_read状态
public void handleaccept(SelectionKey selectionKey) throws Exception{
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
}
public void handleread(SelectionKey selectionKey) throws Exception{
//取消读事件的监控
selectionKey.cancel();
SocketChannel readChannel = (SocketChannel) selectionKey.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear();
readChannel.read(buffer);
System.out.println("服务器端接收到的数据:"+ new String(buffer.array()).trim());
}
public static void main(String[] args) throws Exception {
NioServer server = new NioServer();
server.initServer(8000);
server.listen();
}
}
客户端代码:
package nio;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class NioClient {
public static void main(String[] args) throws Exception {
SocketChannel socketChannel = SocketChannel.open();
InetSocketAddress inetSocketAddress = new InetSocketAddress(8000);
socketChannel.connect(inetSocketAddress);
String msg="我是客户端"+Thread.currentThread().getId();
ByteBuffer buffer=ByteBuffer.allocate(1024);
buffer.put(msg.getBytes());
buffer.flip();
socketChannel.write(buffer);
socketChannel.shutdownOutput();
}
}