import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;
public class AsyncSocketServer {
private ConcurrentHashMap<AsynchronousSocketChannel, ByteBuffer> clientBuffers = new ConcurrentHashMap<>();
public static void main(String[] args) {
new AsyncSocketServer().startServer();
}
public void startServer() {
try (AsynchronousServerSocketChannel serverSocket = AsynchronousServerSocketChannel.open()) {
serverSocket.bind(new InetSocketAddress(5000));
System.out.println("Server started on port 5000");
serverSocket.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
@Override
public void completed(AsynchronousSocketChannel clientSocket, Object attachment) {
serverSocket.accept(null, this);
handleClient(clientSocket);
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
private void handleClient(AsynchronousSocketChannel clientSocket) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
clientBuffers.put(clientSocket, buffer);
clientSocket.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
if (result > 0) {
attachment.flip();
String receivedData = StandardCharsets.UTF_8.decode(attachment).toString();
System.out.println("Received: " + receivedData);
// 处理收到的数据,并发送响应
String response = "Server response: " + receivedData;
ByteBuffer responseBuffer = StandardCharsets.UTF_8.encode(response);
sendDataToClient(clientSocket, responseBuffer);
}
clientSocket.read(attachment, attachment, this);
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
exc.printStackTrace();
}
});
}
public void sendDataToClient(AsynchronousSocketChannel clientSocket, ByteBuffer data) {
clientSocket.write(data, data, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
// 发送成功后的处理逻辑,如果需要的话
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
exc.printStackTrace();
}
});
}
}
在上述代码中:
- 使用
AsynchronousServerSocketChannel
实现异步接受客户端连接。 - 为每个客户端分配缓冲区,并通过回调处理读取和写入操作。
sendDataToClient
方法用于异步发送数据给指定的客户端。
为了进一步提高性能和并发处理能力,可以考虑:
- 优化缓冲区的分配和管理,例如使用循环缓冲区或动态调整大小的缓冲区。
- 引入连接队列和线程池来处理大量并发连接。
- 对数据进行压缩和分包处理,以提高网络传输效率。