/**
* {@inheritDoc}
*/
public void start(int port) throws IOException {
factory = new NioServerSocketChannelFactory();
ServerBootstrap bootstrap = new ServerBootstrap(factory);
bootstrap.setOption("receiveBufferSize", 128 * 1024);
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new SimpleChannelUpstreamHandler() {
@Override
public void childChannelOpen(ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception {
System.out.println("childChannelOpen");
setAttribute(ctx, STATE_ATTRIBUTE, State.WAIT_FOR_FIRST_BYTE_LENGTH);
}
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
System.out.println("channelOpen");
setAttribute(ctx, STATE_ATTRIBUTE, State.WAIT_FOR_FIRST_BYTE_LENGTH);
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
if (e.getMessage() instanceof ChannelBuffer) {
ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
State state = (State) getAttribute(ctx, STATE_ATTRIBUTE);
int length = 0;
if (getAttributesMap(ctx).containsKey(LENGTH_ATTRIBUTE)) {
length = (Integer) getAttribute(ctx, LENGTH_ATTRIBUTE);
}
while (buffer.readableBytes() > 0) {
switch (state) {
case WAIT_FOR_FIRST_BYTE_LENGTH:
length = (buffer.readByte() & 255) << 24;
state = State.WAIT_FOR_SECOND_BYTE_LENGTH;
break;
case WAIT_FOR_SECOND_BYTE_LENGTH:
length += (buffer.readByte() & 255) << 16;
state = State.WAIT_FOR_THIRD_BYTE_LENGTH;
break;
case WAIT_FOR_THIRD_BYTE_LENGTH:
length += (buffer.readByte() & 255) << 8;
state = State.WAIT_FOR_FOURTH_BYTE_LENGTH;
break;
case WAIT_FOR_FOURTH_BYTE_LENGTH:
length += (buffer.readByte() & 255);
state = State.READING;
if ((length == 0) && (buffer.readableBytes() == 0)) {
ctx.getChannel().write(ACK.slice());
state = State.WAIT_FOR_FIRST_BYTE_LENGTH;
}
break;
case READING:
int remaining = buffer.readableBytes();
if (length > remaining) {
length -= remaining;
buffer.skipBytes(remaining);
} else {
buffer.skipBytes(length);
ctx.getChannel().write(ACK.slice());
state = State.WAIT_FOR_FIRST_BYTE_LENGTH;
length = 0;
}
}
}
setAttribute(ctx, STATE_ATTRIBUTE, state);
setAttribute(ctx, LENGTH_ATTRIBUTE, length);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
e.getCause().printStackTrace();
}
});
}
});
bootstrap.bind(new InetSocketAddress(port));
}