我开始使用Netty,但还没有想出如何设置我的协议。
我想要实现的是在一台服务器上处理多个游戏会话。
ChannelGroup
类对我的场景非常有帮助,但我想知道如何在列表上同时发出多个操作时,如果没有服务器抛出ConcurrentModificationException
,我可以设置一个游戏会话列表
public class GameSession {
int id;
ChannelGroup channels;
}
public class MyServerHandler extends ChannelHandlerAdapter{
private List<GameSession> sessions;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if(msg.equals(CREATE_ROOM))
{
sessions.add(new GameSession());
}
else if(msg.equals(JOIN_ROOM))
{
// look for specific room...
// loop here can collide with the above block and throw ConcurrentModificationException
}
}
}
我是否正确地思考它?我该如何实现这种行为?
答案 0 :(得分:0)
您可以将GameSession对象保存在Map中,从Channel到GameSession。
public class MyServerHandler extends ChannelHandlerAdapter{
private Map<Channel, GameSession> sessions;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if(msg.equals(CREATE_ROOM))
{
sessions.put(ctx.channel(), new GameSession());
}
else if(msg.equals(JOIN_ROOM))
{
GameSession session = sessions.get(ctx.channel());
// Could check if the key exists, or if the session is null, etc.
}
}
}