我有一个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);
被发送到另一个客户端(而不是第一个通过循环发送的客户端)!
我错过了什么吗?
答案 0 :(得分:0)
“第一个”是什么意思? ChannelGroup是一个Set,它不保证在迭代时维护插入顺序。