我已经读到可以使用选择器和通道创建一个只有一个线程的多客户端服务器。我做了一个快速草图来测试功能,它似乎只能处理每个连接的套接字数据......我的意思是第一个客户端连接并且服务器正在等待来自它的数据包如果另一个客户端连接它不处理它...任何帮助?作为最终结果我希望我的服务器监听多个客户端每个客户端将能够连接发送和接收数据到/从服务器,所以如果它发送服务器写:客户端[num]发送这个数据“数据”
继承人的代码:
public static void Startnio() throws Exception
{
ServerSocketChannel ServerChannel = ServerSocketChannel.open();
ServerChannel.configureBlocking(false);
ServerSocket Server = ServerChannel.socket();
Server.bind(new InetSocketAddress(port));
Selector selector = Selector.open();
ServerChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server began listening on port: " + port);
while (true)
{
int num = selector.select();
if (num == 0)
{
continue;
}
Set keys = selector.selectedKeys();
Iterator it = keys.iterator();
while (it.hasNext())
{
SelectionKey key = (SelectionKey) it.next();
if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT)
{
Socket Client = Server.accept();
count++;
System.out.println("Client Connected...." + "you have " + count + " clients connected");
SocketChannel ClientChannel = Client.getChannel();
ClientChannel.configureBlocking(false);
ClientChannel.register(selector, SelectionKey.OP_READ);//read incoming stream
}
else
{
if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ)
{
SocketChannel Client = null;
Client = (SocketChannel) key.channel();
client=Client;
ReadClientStream();
}
}
}
}
}
读取客户端流只是一些标准字节缓冲区。