请使用Nio优化上面的代码
时间: 2024-05-09 21:18:42 浏览: 61
以下是使用NIO优化的代码:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NioServer {
private static final int PORT = 8888;
private static final int BUFFER_SIZE = 1024;
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
while (true) {
SocketChannel socketChannel = serverSocketChannel.accept();
executorService.submit(() -> {
try {
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
while (socketChannel.read(buffer) != -1) {
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
上述代码中,使用了`ServerSocketChannel`和`SocketChannel`代替了原来的`ServerSocket`和`Socket`,并且使用了`ByteBuffer`来进行数据的读写。同时,使用了线程池来处理客户端连接,避免了每个连接都创建一个新线程的问题。
阅读全文