2015-10-20 41 views
0

我開始使用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

ChannelGroup是線程安全的,但List對象不是。嘗試使用Collections.synchronizedList()。 http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29 – jgitter

+0

爲每個遊戲會話你將有幾個頻道? – HCarrasko

+0

@Hector是的。每個會話都有自己的ChannelGroup –

回答

0

您可以將GameSession對象保存在從Channel到GameSession的Map中。

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. 
     } 
    } 
}