java Last Netty 4.1客户端被阻止
我有以下创建Netty 4.1
客户端的方法:
public void runClient() throws Exception {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
final ClientClassHandler cch = new ClientClassHandler();
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("frameDecoder",
new ProtobufVarint32FrameDecoder());
ch.pipeline().addLast("protobufDecoder",
new ProtobufDecoder(Client.MyMessage.getDefaultInstance()));
ch.pipeline().addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
ch.pipeline().addLast("protobufEncoder", new ProtobufEncoder());
ch.pipeline().addLast("handler", cch);
ch.pipeline().addLast(new CommonClassHandler());
}
});
Player player = new Player();
cch.setPlayer(player);
player.createMap();
Channel channel = b.connect(HOST, PORT).sync().channel();
player.setChan(channel);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Waits for user input, then fills the Protocol Buffers build and sends it.
while (channel.isOpen()) {
String input = in.readLine();
player.handleInput(input); // Checks if input is OK and sends it to server
}
channel.closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
但是,当第四个客户端加入服务器时,服务器会启动一个游戏循环,这个循环似乎会阻止最后一个客户端的输入到达服务器
将输入发送到服务器,如下所示:
serverChannel.writeAndFlush(message.build());
但它从来没有到达目的地
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Server.MyMessage req = (Server.MyMessage) msg;
protocol.handleInput(req, ctx); // Checks if input of client is OK
System.out.println(req.getKeyword());
}
方法,并且仅当循环停止或不存在时才执行
我不认为我的服务器会因为一个循环而被阻塞。我是不是错过了什么
# 1 楼答案
造成此问题的原因是,您直接从
channelRead
方法启动游戏循环只要
channelRead
方法中有一个线程,netty就不能接受该通道的其他输入,以防止排序和线程安全错误你应该生成一个自定义线程来处理你的游戏循环,或者连接到组的事件执行器中,为你的循环获取一个专用线程