使用NIO写一个服务端
时间: 2023-07-20 17:08:23 浏览: 117
好的,以下是一个简单的使用NIO写的服务端示例代码:
```java
import java.io.IOException;
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 {
private Selector selector;
public void initServer(int port) throws IOException {
// 创建一个选择器
selector = Selector.open();
// 创建一个服务端通道
ServerSocketChannel serverChannel = ServerSocketChannel.open();
// 配置为非阻塞模式
serverChannel.configureBlocking(false);
// 绑定端口
serverChannel.socket().bind(new InetSocketAddress(port));
// 注册到选择器并监听连接事件
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server start on " + port + "...");
}
public void listen() throws IOException {
while (true) {
// 阻塞直到有事件发生
selector.select();
// 处理事件
Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
while (keys.hasNext()) {
SelectionKey key = keys.next();
keys.remove();
// 如果是新连接事件
if (key.isAcceptable()) {
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel channel = server.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
System.out.println("New connection from " + channel.getRemoteAddress());
}
// 如果是读事件
else if (key.isReadable()) {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);
String msg = new String(buffer.array()).trim();
System.out.println("Receive message from " + channel.getRemoteAddress() + ": " + msg);
}
}
}
}
public static void main(String[] args) throws IOException {
NIOServer server = new NIOServer();
server.initServer(8888);
server.listen();
}
}
```
这个服务端使用了Java NIO的API,可以监听端口,接受客户端连接,并读取客户端发送的消息。稍作修改也可以实现回复客户端消息的功能。需要注意的是,由于NIO是非阻塞的,所以需要在事件到来时进行处理,否则会阻塞线程。
阅读全文