1

I'm implementing a socket server with netty 5.0 for client connection. I need to keep socket connection with each callee at all time and send message to inform the callee identically. Currently I have a self-defined class called "ChannelMapper" which stores the "MAC address" and "ChannelId (as String)" as a relation record in DB. (Since the caller only send "MAC address" of callee as identification to server for connection)

public ChannelMapper(String chid, String macAddr) {
    this.chid = chid;
    this.macAddr = macAddr;
}

Each time when the callee is connected to server, it sends its own MAC address and then server would store a self-defined "ChannelMapper" record for identification. I have a "ChannelGroup" for keeping all connected socket channels. And I also have another Map to keep the real "ChannelId" object since netty doesn't have an API to create "ChannelId" object by the String form of "ChannelId" (says channelId.asLongText())

public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
public static Map<String, ChannelId> mapChannels = new HashMap<>();

Each time a client is connected, it would run method "channelActive" and store the channel info in DB and Map separately for future usage.

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    ChannelId channelId = channel.id();
    String chid = channelId.asLongText();
    channels.add(channel);
    mapChannels.put(chid, channelId);
}

So if server would like to send message to client through socket, I need to query DB to get corresponding "ChannelId" in String form. And then get actual "ChannelId" object stored in Map because the only way to get "ChannelId" is calling the API "Channel find(ChannelId id)" in "ChannelGroup"

ChannelMapper mapper = ChannelMapper.findByMac(macAddr);
if (mapper != null) {
    String chid = mapper.getChid();
    ChannelId channelId = mapChannels.get(chid);
    Channel channel = channels.find(channelId);
}

I'd like to ask if there's a better way to store and retrieve the actual "Channel" object? And would it be better if I change Map<String, ChannelId> to Map<String, Channel> to store "Channel" directly?

Alvin
  • 21
  • 4
  • After consulting with my colleagues, I've modified to use Map whose key is "macAddr" and the value is "Channel" object. Without storing record in DB and no ChannelId is kept. – Alvin Feb 18 '16 at 08:29

0 Answers0