Skip to content

Instantly share code, notes, and snippets.

@Karry
Last active August 29, 2015 13:58
Show Gist options
  • Save Karry/9955752 to your computer and use it in GitHub Desktop.
Save Karry/9955752 to your computer and use it in GitHub Desktop.
Netty example that blocks events from other sockets.
package cz.karry;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioWorkerPool;
import org.jboss.netty.handler.codec.http.*;
import org.jboss.netty.handler.stream.ChunkedInput;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
class InfiniteZeroStreamHandler extends SimpleChannelHandler {
final byte[] zeros = new byte[1024];
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
Object msg = e.getMessage();
if (msg instanceof HttpMessage){
ChunkedInput payload = new ChunkedInput() {
@Override
public boolean hasNextChunk() throws Exception {
return true;
}
@Override
public Object nextChunk() throws Exception {
Thread.sleep(100);
return new DefaultHttpChunk( ChannelBuffers.wrappedBuffer(zeros) );
}
@Override
public boolean isEndOfInput() throws Exception {
return false;
}
@Override
public void close() throws Exception {
}
};
DefaultHttpMessage response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.setChunked(true);
response.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
//message = new HttpChunkedInput((ChunkedInput) payload, headResponse);
ctx.getChannel().write(response);
ctx.getChannel().write(payload);
} else {
super.messageReceived(ctx, e);
}
}
}
public class Main {
public static void main(String[] args){
int port = 8080;
String host = "0.0.0.0";
NioServerSocketChannelFactory socketChannelFactory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(), new NioWorkerPool(Executors.newCachedThreadPool(), 1)) ;
ServerBootstrap bootstrap = new ServerBootstrap(socketChannelFactory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline () {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("HttpRequestDecoder", new HttpRequestDecoder());
pipeline.addLast("HttpResponseEncoder", new HttpResponseEncoder());
pipeline.addLast("HttpChunkAggregator", new HttpChunkAggregator(1 * 1024 * 1024));
pipeline.addLast("Streamer", new ChunkedWriteHandler());
pipeline.addLast("InfiniteZeroStreamHandler", new InfiniteZeroStreamHandler());
return pipeline;
}
});
bootstrap.bind(new InetSocketAddress(host, port ));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment