我有以下创建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());
}
方法,仅在循环停止或不存在时执行。
我没想到我的服务器因为循环而被阻止了。我错过了什么吗?
答案 0 :(得分:0)
导致此问题的原因是您从channelRead
方法直接启动游戏循环。
只要1个线程在channelRead
方法中,netty就不会接受该通道的其他输入,以防止排序和线程安全错误。
你应该生成一个自定义线程来处理你的游戏循环,或者挂钩到组的事件执行器来获得你的循环的专用线程。