List of usage examples for io.netty.channel ChannelInitializer ChannelInitializer
ChannelInitializer
From source file:com.sixmac.imspeak.app.WebSocketClient.java
License:Apache License
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "ws" : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("ws".equalsIgnoreCase(scheme)) { port = 80;/* w w w . j av a 2 s .com*/ } else if ("wss".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { System.err.println("Only WS(S) is supported."); return; } final boolean ssl = "wss".equalsIgnoreCase(scheme); final SslContext sslCtx; EventLoopGroup group = new NioEventLoopGroup(); try { // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler); } }); Channel ch = b.connect(uri.getHost(), port).sync().channel(); handler.handshakeFuture().sync(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); while (true) { String msg = console.readLine(); if (msg == null) { break; } else if ("bye".equals(msg.toLowerCase())) { ch.writeAndFlush(new CloseWebSocketFrame()); ch.closeFuture().sync(); break; } else if ("ping".equals(msg.toLowerCase())) { WebSocketFrame frame = new PingWebSocketFrame( Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 })); ch.writeAndFlush(frame); } else { WebSocketFrame frame = new TextWebSocketFrame(msg); ch.writeAndFlush(frame); } } } finally { group.shutdownGracefully(); } }
From source file:com.slyak.services.proxy.handler.Socks5CommandRequestHandler.java
License:Apache License
@Override protected void channelRead0(final ChannelHandlerContext requestChannelContext, final DefaultSocks5CommandRequest msg) throws Exception { if (Socks5CommandType.CONNECT.equals(msg.type())) { log.debug("Start to connect remote server : {}:{}", msg.dstAddr(), msg.dstPort()); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(remoteEventLoopGroup).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override//from ww w . ja va 2 s .com protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new IdleStateHandler(0, 0, 30)); pipeline.addLast(new IdleEventHandler()); pipeline.addLast(new Remote2RequestHandler(requestChannelContext.channel())); pipeline.addLast(ExceptionHandler.INSTANCE); } }); final ChannelFuture future = bootstrap.connect(msg.dstAddr(), msg.dstPort()); this.remoteChannel = future.channel(); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture connectFuture) throws Exception { if (connectFuture.isSuccess()) { log.debug("Connected to remote server"); requestChannelContext.pipeline().addLast(new Request2RemoteHandler(remoteChannel)); Socks5CommandResponse response = new DefaultSocks5CommandResponse( Socks5CommandStatus.SUCCESS, Socks5AddressType.IPv4); //add client to dest handler to receive response requestChannelContext.writeAndFlush(response); } else { log.debug("Failed to connect to remote server"); Socks5CommandResponse commandResponse = new DefaultSocks5CommandResponse( Socks5CommandStatus.FAILURE, Socks5AddressType.IPv4); requestChannelContext.writeAndFlush(commandResponse); } } }); } else { log.debug("Fire channel read"); requestChannelContext.fireChannelRead(msg); } }
From source file:com.slyak.services.proxy.server.NettyProxyServer.java
License:Apache License
@SneakyThrows(InterruptedException.class) public void start() { ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED); ServerBootstrap bootstrap = new ServerBootstrap(); bossGroup = new NioEventLoopGroup(proxyProperties.getBoss()); workerGroup = new NioEventLoopGroup(proxyProperties.getWorker()); clientGroup = new NioEventLoopGroup(proxyProperties.getClient()); try {// w w w.j a v a2 s .c om bootstrap.group(bossGroup, workerGroup).channel(getChannelClass()) .option(ChannelOption.SO_BACKLOG, proxyProperties.getBackLog()) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, proxyProperties.getConnectTimeout()) .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_REUSEADDR, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //channel time out handler pipeline.addLast(new IdleStateHandler(0, 0, 30)); pipeline.addLast(new IdleEventHandler()); //logging pipeline.addLast(new LoggingHandler()); if (isRouter()) { pipeline.addLast(getProxyHandler(proxyProperties)); } else { pipeline.addLast(getCustomChannelHandlers(clientGroup)); } pipeline.addLast(ExceptionHandler.INSTANCE); } }); //start server ChannelFuture future = bootstrap.bind(proxyProperties.getPort()).sync(); log.debug("Starting proxy server , port is {}", proxyProperties.getPort()); future.channel().closeFuture().sync(); } finally { stop(); } }
From source file:com.spotify.ffwd.carbon.CarbonLineServer.java
License:Apache License
@Override public ChannelInitializer<Channel> initializer() { return new ChannelInitializer<Channel>() { @Override/* w w w . jav a 2 s. c om*/ protected void initChannel(final Channel ch) throws Exception { ch.pipeline().addLast(new LineBasedFrameDecoder(MAX_LINE)); ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8)); ch.pipeline().addLast(decoder, handler); } }; }
From source file:com.spotify.ffwd.debug.NettyDebugServer.java
License:Apache License
public AsyncFuture<Void> start() { final ResolvableFuture<Void> future = async.future(); final ServerBootstrap s = new ServerBootstrap(); s.channel(NioServerSocketChannel.class); s.group(boss, worker);//from w ww .ja va 2 s . co m s.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) throws Exception { connected.add(ch); log.info("Connected {}", ch); ch.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { connected.remove(ch); log.info("Disconnected {}", ch); } }); } }); s.bind(localAddress).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (!f.isSuccess()) { future.fail(f.cause()); return; } log.info("Bound to {}", localAddress); if (!server.compareAndSet(null, f.channel())) { f.channel().close(); future.fail(new IllegalStateException("server already started")); return; } future.resolve(null); } }); return future; }
From source file:com.spotify.ffwd.http.HttpProtocolServer.java
License:Apache License
@Override public final ChannelInitializer<Channel> initializer() { return new ChannelInitializer<Channel>() { @Override/*from w w w . j a v a2s. c o m*/ protected void initChannel(Channel ch) throws Exception { final ChannelInboundHandlerAdapter exceptionHandler = new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { if (cause instanceof HttpException) { final HttpException e = (HttpException) cause; sendResponse(ctx, e.getStatus()); return; } if (cause instanceof DecoderException) { exceptionCaught(ctx, cause.getCause()); return; } log.error("error in pipeline: ", cause); sendResponse(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); } }; ch.pipeline().addLast(new HttpRequestDecoder(), new HttpContentDecompressor(), new HttpObjectAggregator(Integer.MAX_VALUE), decoder, exceptionHandler, handler); ch.pipeline().addLast(new HttpResponseEncoder()); } }; }
From source file:com.spotify.ffwd.json.JsonFrameProtocolServer.java
License:Apache License
@Override public final ChannelInitializer<Channel> initializer() { return new ChannelInitializer<Channel>() { @Override//from ww w . j a v a2 s . com protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new DatagramPacketToByteBuf()); ch.pipeline().addLast(decoder, handler); } }; }
From source file:com.spotify.ffwd.json.JsonLineProtocolServer.java
License:Apache License
@Override public final ChannelInitializer<Channel> initializer() { return new ChannelInitializer<Channel>() { @Override/*from w w w. j av a 2 s . co m*/ protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new LineBasedFrameDecoder(MAX_LINE)); ch.pipeline().addLast(decoder, handler); } }; }
From source file:com.spotify.ffwd.protobuf.ProtobufFrameProtocolServer.java
License:Apache License
@Override public final ChannelInitializer<Channel> initializer() { return new ChannelInitializer<Channel>() { @Override/*from w w w. j a v a 2 s .c o m*/ protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new DatagramPacketToByteBuf(), decoder, handler); } }; }
From source file:com.spotify.ffwd.protobuf.ProtobufLengthPrefixedProtocolServer.java
License:Apache License
@Override public final ChannelInitializer<Channel> initializer() { return new ChannelInitializer<Channel>() { @Override/*ww w . j a v a2 s . co m*/ protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(MAX_LENGTH, 0, 4), decoder, handler); } }; }