All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.nadron.handlers.netty.MessageBufferEventEncoder Maven / Gradle / Ivy

Go to download

Nadron is a high speed socket based java game server written using Netty and Mike Rettig's Jetlang. It is specifically tuned for network based multiplayer games and supports TCP and UDP network protocols.

There is a newer version: 0.7
Show newest version
package io.nadron.handlers.netty;

import io.nadron.communication.MessageBuffer;
import io.nadron.event.Event;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.MessageList;
import io.netty.handler.codec.MessageToMessageEncoder;



@Sharable
public class MessageBufferEventEncoder extends MessageToMessageEncoder
{

	@Override
	protected void encode(ChannelHandlerContext ctx, Event event,
			MessageList out) throws Exception
	{
		out.add(encode(ctx, event));
	}
	
	/**
	 * Encode is separated out so that child classes can still reuse this
	 * functionality.
	 * 
	 * @param ctx
	 * @param event
	 *            The event to be encoded into {@link ByteBuf}. It will be
	 *            converted to 'opcode'-'payload' format.
	 * @return If only opcode is specified a single byte {@link ByteBuf} is
	 *         returned, otherwise a byte buf with 'opcode'-'payload' format is
	 *         returned.
	 */
	protected ByteBuf encode(ChannelHandlerContext ctx, Event event)
	{
		ByteBuf msg = null;
		if(null != event.getSource())
		{
			@SuppressWarnings("unchecked")
			MessageBuffer msgBuffer = (MessageBuffer)event.getSource();
			ByteBuf data = msgBuffer.getNativeBuffer();
			msg = ctx.alloc().buffer(1 + data.readableBytes());
			msg.writeByte(event.getType());
			msg.writeBytes(data);
		}
		else
		{
			msg = ctx.alloc().buffer(1);
			msg.writeByte(event.getType());
		}
		return msg;
	}

}