List of usage examples for io.netty.channel ChannelHandlerContext fireChannelRead
@Override ChannelHandlerContext fireChannelRead(Object msg);
From source file:com.github.zk1931.jzab.transport.NettyTransportTest.java
License:Apache License
@Test(timeout = 10000) public void testTieBreaker() throws Exception { final String peerA = getUniqueHostPort(); final String peerB = getUniqueHostPort(); final CountDownLatch disconnectedA = new CountDownLatch(1); final CountDownLatch disconnectedB = new CountDownLatch(1); Transport.Receiver receiverA = new Transport.Receiver() { public void onReceived(String source, Message message) { Assert.fail("Handshake should have failed"); }//from ww w . ja v a 2s .c om public void onDisconnected(String source) { LOG.debug("Got disconnected from {}", source); disconnectedA.countDown(); } }; Transport.Receiver receiverB = new Transport.Receiver() { public void onReceived(String source, Message message) { Assert.fail("Handshake should have failed"); } public void onDisconnected(String source) { LOG.debug("Got disconnected from {}", source); disconnectedB.countDown(); } }; final NettyTransport transportA = new NettyTransport(peerA, receiverA, getDirectory()); final NettyTransport transportB = new NettyTransport(peerB, receiverB, getDirectory()); transportB.channel.pipeline().addFirst(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // B initiates another handshake before responding to A's handshake. transportB.send(peerA, createAck(new Zxid(0, 0))); ctx.pipeline().remove(this); ctx.fireChannelRead(msg); } }); // A initiates a handshake. transportA.send(peerB, createAck(new Zxid(0, 0))); disconnectedA.await(); disconnectedB.await(); transportA.shutdown(); transportB.shutdown(); }
From source file:com.gxkj.demo.netty.socksproxy.SocksServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, SocksRequest socksRequest) throws Exception { switch (socksRequest.requestType()) { case INIT: {/*from w w w .ja v a2 s . co m*/ // auth support example // ctx.pipeline().addFirst("socksAuthRequestDecoder",new SocksAuthRequestDecoder()); // ctx.write(new SocksInitResponse(SocksMessage.SocksAuthScheme.AUTH_PASSWORD)); ctx.pipeline().addFirst(SocksCmdRequestDecoder.getName(), new SocksCmdRequestDecoder()); ctx.write(new SocksInitResponse(SocksAuthScheme.NO_AUTH)); break; } case AUTH: ctx.pipeline().addFirst(SocksCmdRequestDecoder.getName(), new SocksCmdRequestDecoder()); ctx.write(new SocksAuthResponse(SocksAuthStatus.SUCCESS)); break; case CMD: SocksCmdRequest req = (SocksCmdRequest) socksRequest; if (req.cmdType() == SocksCmdType.CONNECT) { ctx.pipeline().addLast(SocksServerConnectHandler.getName(), new SocksServerConnectHandler()); ctx.pipeline().remove(this); ctx.fireChannelRead(socksRequest); } else { ctx.close(); } break; case UNKNOWN: ctx.close(); break; } }
From source file:com.hazelcast.simulator.protocol.handler.ConnectionHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception { if (!(obj instanceof ByteBuf)) { return;//from w w w. j a v a 2s. co m } ByteBuf buf = (ByteBuf) obj; if (buf.readableBytes() < MINIMUM_BYTE_BUFFER_SIZE) { return; } if (!isSimulatorMessage(buf) && !isResponse(buf)) { LOGGER.warn(format("Invalid connection from %s (no magic bytes found)", ctx.channel().remoteAddress())); ctx.close(); return; } // the connection is valid so we remove this handler and forward the buffer to the pipeline LOGGER.info(format("Valid connection from %s (magic bytes found)", ctx.channel().remoteAddress())); isConnectionValid.countDown(); ctx.pipeline().remove(this); ctx.fireChannelRead(obj); ctx.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { connectionListener.disconnected(future.channel()); } }); connectionListener.connected(ctx.channel()); }
From source file:com.hazelcast.simulator.protocol.handler.ConnectionValidationHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception { if (!(obj instanceof ByteBuf)) { return;/*from ww w . j a v a 2s . c o m*/ } ByteBuf buf = (ByteBuf) obj; if (buf.readableBytes() < MINIMUM_BYTE_BUFFER_SIZE) { return; } if (!isSimulatorMessage(buf) && !isResponse(buf)) { LOGGER.warn(format("Invalid connection from %s (no magic bytes found)", ctx.channel().remoteAddress())); ctx.close(); return; } // the connection is valid so we remove this handler and forward the buffer to the pipeline LOGGER.info(format("Valid connection from %s (magic bytes found)", ctx.channel().remoteAddress())); ctx.pipeline().remove(this); ctx.fireChannelRead(obj); }
From source file:com.heelenyc.im.client.handler.ClientHeartBeatReqHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { Message message = (Message) msg;//from ww w .j av a 2 s.co m // ????? if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) { heartBeat = ctx.executor().scheduleAtFixedRate(new ClientHeartBeatReqHandler.HeartBeatTask(ctx), 0, Constans.HEARTBEAT_PERIOD_INMS, TimeUnit.MILLISECONDS); } else if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) { logger.info("Client receive server heart beat message : ---> " + message); } else ctx.fireChannelRead(msg); }
From source file:com.heelenyc.im.client.handler.ClientLoginAuthReqHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { Message message = (Message) msg;//from www . ja va2 s . c o m // ?????? if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) { byte loginResult = (byte) message.getBody(); if (loginResult != (byte) 0) { // ? ctx.close(); } else { logger.info("Login is ok : " + message); ctx.fireChannelRead(msg); } } else ctx.fireChannelRead(msg); }
From source file:com.heliosapm.tsdblite.handlers.http.HttpRequestManager.java
License:Apache License
/** * {@inheritDoc}/*from w ww . j a va 2 s. co m*/ * @see io.netty.channel.SimpleChannelInboundHandler#channelRead0(io.netty.channel.ChannelHandlerContext, java.lang.Object) */ @Override protected void channelRead0(final ChannelHandlerContext ctx, final HttpRequest msg) throws Exception { try { final String uri = msg.uri(); final Channel channel = ctx.channel(); if (uri.endsWith("/favicon.ico")) { final DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, favicon); resp.headers().set(HttpHeaders.CONTENT_TYPE, "image/x-icon"); resp.headers().setInt(HttpHeaders.CONTENT_LENGTH, favSize); ctx.writeAndFlush(resp); return; } else if (uri.equals("/api/put") || uri.equals("/api/metadata")) { final ChannelPipeline p = ctx.pipeline(); // p.addLast(loggingHandler, jsonAdapter, new JsonObjectDecoder(true), traceHandler); p.addLast(jsonAdapter, new JsonObjectDecoder(true), traceHandler); // if(msg instanceof FullHttpRequest) { // ByteBuf b = ((FullHttpRequest)msg).content().copy(); // ctx.fireChannelRead(b); // } ctx.fireChannelRead(msg); p.remove("requestManager"); log.info("Switched to JSON Trace Processor"); return; } final TSDBHttpRequest r = new TSDBHttpRequest(msg, ctx.channel(), ctx); final HttpRequestHandler handler = requestHandlers.get(r.getRoute()); if (handler == null) { r.send404().addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(Future<? super Void> f) throws Exception { log.info("404 Not Found for {} Complete: success: {}", r.getRoute(), f.isSuccess()); if (!f.isSuccess()) { log.error("Error sending 404", f.cause()); } }; }); return; } handler.process(r); } catch (Exception ex) { log.error("HttpRequest Routing Error", ex); } }
From source file:com.heren.turtle.entry.channel.handler.LoginAuthRespHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String message = (String) msg; System.out.println(message);//from w w w . jav a 2s . c om String username = LoadUtils.getMessageValue(message, LoadUtils.TYPE_USERNAME); String password = LoadUtils.getMessageValue(message, LoadUtils.TYPE_PASSWORD); String token = LoadUtils.getMessageValue(message, LoadUtils.TYPE_USER_TOKEN); List<String> refuseIPAddress = Any.getRefuseAddress(); InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress(); String remoteAddress = address.getAddress().getHostAddress(); boolean refuseStatus = !refuseIPAddress.contains(remoteAddress); if (refuseStatus) { if (token.equals(Any.getToken())) { Map<String, String> useInfo = Any.getUseInfo(); boolean usernameContain = useInfo.containsKey(username); if (usernameContain) { if (!useInfo.get(username).equals(password)) { Map<String, String> newUseInfo = Any.getUseInfo(); if (newUseInfo == null || !newUseInfo.containsKey(username) || !newUseInfo.get(username).equals(password)) { Any.recordRefuseIp(remoteAddress); loginResp = LoadUtils.resultMessage(message, ExceptionConstant.INCORRECT_PASSWORD, "exception,incorrect password"); ctx.writeAndFlush(loginResp); } } } else { loginResp = LoadUtils.resultMessage(message, ExceptionConstant.INCORRECT_USERNAME, "exception,incorrect username"); ctx.writeAndFlush(loginResp); } } else { loginResp = LoadUtils.resultMessage(message, ExceptionConstant.INCORRECT_TOKEN, "exception," + "incorrect token"); ctx.writeAndFlush(loginResp); } } else { loginResp = LoadUtils.resultMessage(message, ExceptionConstant.TOO_MANY_TIME, "wrong too many " + "times ,this is ip address(" + remoteAddress + ") not allow to login"); ctx.writeAndFlush(loginResp); } ctx.fireChannelRead(msg); }
From source file:com.hop.hhxx.example.http2.helloworld.multiplex.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 *///ww w . j av a2 s . c o m private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast(sourceCodec); p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory)); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(msg); } }); p.addLast(new UserEventLogger()); }
From source file:com.hxr.javatone.nettyguide.d12.server.LoginAuthRespHandler.java
License:Apache License
/** * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to * the next {@link ChannelHandler} in the {@link ChannelPipeline}. * // w ww . ja va 2 s. com * Sub-classes may override this method to change behavior. */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyMessage message = (NettyMessage) msg; // ????? if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_REQ.value()) { String nodeIndex = ctx.channel().remoteAddress().toString(); NettyMessage loginResp = null; // ??? if (nodeCheck.containsKey(nodeIndex)) { loginResp = buildResponse((byte) -1); } else { InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress(); String ip = address.getAddress().getHostAddress(); boolean isOK = false; for (String WIP : whitekList) { if (WIP.equals(ip)) { isOK = true; break; } } loginResp = isOK ? buildResponse((byte) 0) : buildResponse((byte) -1); if (isOK) { nodeCheck.put(nodeIndex, true); } } System.out.println("The login response is : " + loginResp + " body [" + loginResp.getBody() + "]"); ctx.writeAndFlush(loginResp); } else { ctx.fireChannelRead(msg); } }