com.witjit.game.server.communication.netty.handler.AbstractMessageInHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.witjit.game.server.communication.netty.handler.AbstractMessageInHandler.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.witjit.game.server.communication.netty.handler;

import com.witjit.game.server.communication.core.Message;
import com.witjit.game.server.communication.core.MessageDispatcher;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 *
 * @author Administrator
 */
public abstract class AbstractMessageInHandler<M> extends ChannelInboundHandlerAdapter {

    private final MessageDispatcher<M> messageDispatcher;

    public AbstractMessageInHandler(MessageDispatcher<M> messageDispatcher) {
        this.messageDispatcher = messageDispatcher;
    }

    /**
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof ByteBuf)) {
            //TODO: handle error message.
            return;
        }

        ByteBuf mb = (ByteBuf) msg;
        long receiver = readEndpointId(mb);
        long sender = readEndpointId(mb);
        M content = readMessage(mb);
        Message<M> message = new Message(receiver, sender, content);
        messageDispatcher.dispatch(message);
    }

    protected abstract long readEndpointId(ByteBuf mb);

    protected abstract M readMessage(ByteBuf mb);
}