Package net.yura.lobby.netty

Source Code of net.yura.lobby.netty.MessageHandler

package net.yura.lobby.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import java.util.logging.Level;
import net.yura.lobby.model.Message;
import net.yura.lobby.server.LobbyServer;
import net.yura.lobby.server.LobbySession;

/**
* @author Yura Mamyrin
*/
public class MessageHandler extends ChannelInboundHandlerAdapter {
   
    final LobbyServer server;
    final ChannelGroup allClientChannels;
   
    public MessageHandler(LobbyServer server,ChannelGroup allClientChannels) {
        this.server = server;
        this.allClientChannels = allClientChannels;
    }
   
    @Override
    public void channelRead(ChannelHandlerContext chc, Object msg) throws Exception {
        LobbySession session = getLobbySession(chc);
        server.handleMessage(session, (Message)msg);
    }
   
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        LobbySession session = getLobbySession(ctx);
        Server.logger.log(Level.WARNING, "exception "+ctx+" "+session, cause);
        ctx.close();
    }



    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
       
        LobbySession session = new LobbySession();
        ctx.channel().attr(Server.SESSION_KEY).set(session);
       
        Server.logger.info("channelRegistered "+ctx+" "+session);
       
        allClientChannels.add(ctx.channel());
        server.gotConnected(session);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
       
        LobbySession session = getLobbySession(ctx);
       
        Server.logger.info("channelUnregistered "+ctx+" "+session);
       
        allClientChannels.remove(ctx.channel()); // TODO not sure if needed
        server.closingConnection(session);
    }
   
    private LobbySession getLobbySession(ChannelHandlerContext ctx) {
        return ctx.channel().attr(Server.SESSION_KEY).get();
    }

}
TOP

Related Classes of net.yura.lobby.netty.MessageHandler

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.