ChannelGroup在Netty 4.1.6中无法正常工作

时间:2016-11-22 22:10:43

标签: java netty

我有一个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的对象中,并初始化一个游戏循环,让每个客户都有机会发挥作用:

    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);被发送到另一个客户端(而不是第一个通过循环发送的客户端)!

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

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