繁体   English   中英

ChannelGroup无法按Netty 4.1.6的预期工作

[英]ChannelGroup not working as intended in Netty 4.1.6

我有一个ChannelGroup含4个客户机已经在逐一记录和已被添加到该组,因为他们通过Netty的方法登录handlerAdded

static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); 

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    channels.add(ctx.channel());
    assignGroup(ctx.channel());
}

稍后,我将ChannelGroup保存在一个名为GameMaster的对象中,并初始化一个游戏循环,使每个客户都有机会ChannelGroup游戏:

    static ChannelGroup channels; // contains the actual channels, saved in contructor

    public void bettingPhase(boolean isOk) {
    int i = 0;
    int y = 0;

    for (Channel chan : channels) { // Should start on the first client that logged in
        Server.MyMessage.Builder message = Server.MyMessage.newBuilder();
        message.setKeyword("304");
        message.setValue("Please input a contract:");
        chan.writeAndFlush(message); // PROBLEM HERE
        while (isOk == false) { // Loop to check the playing client's input
            Server.MyMessage.Builder message2 = Server.MyMessage.newBuilder();
            try {
                Thread.sleep(1000);
                if (playerAnswer.getKeyword().equals("CONTRACT")) {
                    System.out.println("Player has inputed contract.");
                    i++;
                    message2.setKeyword("310");
                    chan.writeAndFlush(message); // Tells the current client his turn is over
                    System.out.println("End of turn for player.");
                    for (Channel channel : channels) { // Loop to tell the next client it's his turn
                        if (y == i) {
                            message2.setKeyword("309");
                            channel.writeAndFlush(message);
                            System.out.println("Start of turn for player.");
                        }
                        y++;
                    }
                    isOk = true;
                    playerAnswer.clearKeyword();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        isOk = false;
    }
}

请原谅这段代码。

但是由于某种原因,我的句子"304 Please input a contract:"通过chan.writeAndFlush(message); 被发送到另一个客户端(而不是第一个客户端,因为它应该通过循环发送)!

我想念什么吗?

“第一个”是什么意思? ChannelGroup是一个Set,它不能保证在迭代时保持插入顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM