List of usage examples for io.netty.channel ChannelHandlerContext channel
Channel channel();
From source file:cn.savor.small.netty.NettyClientHandler.java
License:Open Source License
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { super.userEventTriggered(ctx, evt); String channelId = ctx.channel().id().toString(); if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state().equals(IdleState.READER_IDLE)) { //?//from w w w .j a v a 2s .c o m LogUtils.i("READER_IDLE"); LogFileUtil.write("NettyClientHandler READER_IDLE"); } else if (event.state().equals(IdleState.WRITER_IDLE)) { LogUtils.i("WRITER_IDLE"); LogFileUtil.write("NettyClientHandler WRITER_IDLE"); //?REQ========== LogUtils.i("ALL_IDLE"); // ??? MessageBean message = new MessageBean(); message.setCmd(MessageBean.Action.HEART_CLENT_TO_SERVER); String number = channelId + System.currentTimeMillis(); message.setSerialnumber(number); message.setIp(AppUtils.getLocalIPAddress()); message.setMac(session.getEthernetMac()); InnerBean bean = new InnerBean(); bean.setHotelId(session.getBoiteId()); bean.setRoomId(session.getRoomId()); bean.setSsid(AppUtils.getShowingSSID(mContext)); bean.setBoxId(session.getBoxId()); ArrayList<String> contList = new ArrayList<String>(); contList.add("I am a Heart Pakage..."); contList.add(new Gson().toJson(bean)); message.setContent(contList); ctx.writeAndFlush(message); LogUtils.v("????====" + channelId + "====>>>>.....??:" + message.getSerialnumber()); LogFileUtil.write("NettyClientHandler ????====" + channelId + "====>>>>.....??:" + message.getSerialnumber()); } else if (event.state().equals(IdleState.ALL_IDLE)) { // close(ctx); } } }
From source file:cn.savor.small.netty.NettyClientHandler.java
License:Open Source License
public void reconnect(ChannelHandlerContext ctx) { try {/* w w w .j a v a 2 s. c o m*/ final EventLoop loop = ctx.channel().eventLoop(); loop.schedule(new Runnable() { @Override public void run() { LogUtils.i("Reconnecting to: " + session.getNettyUrl() + ':' + session.getNettyPort()); nettyClient.start(); } }, 5L, TimeUnit.SECONDS); } catch (Exception ex) { ex.toString(); } }
From source file:cn.scujcc.bug.bitcoinplatformandroid.util.socket.websocket.WebSocketClientHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel(); moniter.updateTime();/*from w ww. j av a2 s. com*/ if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; service.onReceive(textFrame.text()); } else if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame; service.onReceive(decodeByteBuff(binaryFrame.content())); } else if (frame instanceof PongWebSocketFrame) { System.out.println("WebSocket Client received pong"); } else if (frame instanceof CloseWebSocketFrame) { System.out.println("WebSocket Client received closing"); ch.close(); } }
From source file:cn.wantedonline.puppy.httpserver.component.BasePageDispatcher.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (AssertUtil.isNotNull(msg)) { ContextAttachment attach = getAttach(ctx); try {/* ww w. j ava2s .c o m*/ if (msg instanceof HttpMessage) { HttpRequest request = null; if (msg instanceof AggregatedFullHttpMessage) { AggregatedFullHttpMessage aggregatedFullHttpMessage = (AggregatedFullHttpMessage) msg; request = (HttpRequest) aggregatedFullHttpMessage.message; } else { request = (HttpRequest) msg; } request.setRemoteAddress(ctx.channel().remoteAddress()); request.setLocalAddress(ctx.channel().localAddress()); attach.registerNewMessage(request); requestReceived(ctx, attach); } } catch (Exception e) { e.printStackTrace(); } finally { ChannelFuture future = ctx.writeAndFlush(attach.getResponse().copy()); attach.markWriteEnd(); // config.countStat.responseSended(ctx, attach); // config.timeSpanStat.writeEnd(attach); future.addListener(attach); } } }
From source file:cn.yesway.demo.book.protocol.netty.server.LoginAuthRespHandler.java
License:Apache License
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace();// w w w . ja va 2s . c om nodeCheck.remove(ctx.channel().remoteAddress().toString());// ctx.close(); ctx.fireExceptionCaught(cause); }
From source file:co.paralleluniverse.comsat.webactors.netty.WebActorHandler.java
License:Open Source License
@Override public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (ctx.channel().isOpen()) ctx.close();//from w w w.ja v a 2 s . c o m log.error("Exception caught", cause); }
From source file:co.paralleluniverse.comsat.webactors.netty.WebActorHandler.java
License:Open Source License
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return;/* w w w. ja v a 2 s .c om*/ } if (frame instanceof PingWebSocketFrame) { ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof ContinuationWebSocketFrame) return; if (frame instanceof TextWebSocketFrame) webSocketActor.onMessage(((TextWebSocketFrame) frame).text()); else webSocketActor.onMessage(frame.content().nioBuffer()); }
From source file:co.paralleluniverse.comsat.webactors.netty.WebActorHandler.java
License:Open Source License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws SuspendExecution, InterruptedException { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpError(ctx, req, new DefaultFullHttpResponse(req.getProtocolVersion(), BAD_REQUEST)); return;/* w w w.j a v a2s .co m*/ } final String uri = req.getUri(); final Context actorCtx = contextProvider.get(req); assert actorCtx != null; final String sessionId = actorCtx.getId(); assert sessionId != null; final ReentrantLock lock = actorCtx.getLock(); assert lock != null; lock.lock(); try { final ActorRef<? extends WebMessage> userActorRef = actorCtx.getWebActor(); ActorImpl internalActor = (ActorImpl) actorCtx.getAttachments().get(ACTOR_KEY); if (userActorRef != null) { if (actorCtx.handlesWithWebSocket(uri)) { if (internalActor == null || !(internalActor instanceof WebSocketActorAdapter)) { //noinspection unchecked webSocketActor = new WebSocketActorAdapter(ctx, (ActorRef<? super WebMessage>) userActorRef); addActorToContextAndUnlock(actorCtx, webSocketActor, lock); } // Handshake final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(uri, null, true); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { @SuppressWarnings("unchecked") final ActorRef<WebMessage> userActorRef0 = (ActorRef<WebMessage>) webSocketActor.userActor; handshaker.handshake(ctx.channel(), req) .addListener(new GenericFutureListener<ChannelFuture>() { @Override @Suspendable public void operationComplete(ChannelFuture future) throws Exception { userActorRef0.send( new WebSocketOpened(WebActorHandler.this.webSocketActor.ref())); } }); } return; } else if (actorCtx.handlesWithHttp(uri)) { if (internalActor == null || !(internalActor instanceof HttpActorAdapter)) { //noinspection unchecked internalActor = new HttpActorAdapter((ActorRef<HttpRequest>) userActorRef, actorCtx, httpResponseEncoderName); addActorToContextAndUnlock(actorCtx, internalActor, lock); } //noinspection unchecked ((HttpActorAdapter) internalActor) .handleRequest(new HttpRequestWrapper(internalActor.ref(), ctx, req, sessionId)); return; } } } finally { if (lock.isHeldByCurrentStrand() && lock.isLocked()) lock.unlock(); } sendHttpError(ctx, req, new DefaultFullHttpResponse(req.getProtocolVersion(), NOT_FOUND)); }
From source file:co.rsk.net.discovery.PacketDecoder.java
License:Open Source License
public DiscoveryEvent decodeMessage(ChannelHandlerContext ctx, byte[] encoded, InetSocketAddress sender) { try {//from w w w .j a v a 2s . c o m PeerDiscoveryMessage msg = MessageDecoder.decode(encoded); return new DiscoveryEvent(msg, sender); } catch (Exception e) { logger.error("Exception processing inbound message from {} : {}", ctx.channel().remoteAddress(), Hex.toHexString(encoded), e); throw e; } }
From source file:co.rsk.net.discovery.PacketDecoderTest.java
License:Open Source License
@Test(expected = PeerDiscoveryException.class) public void decodeInvalidMessage() throws Exception { PacketDecoder decoder = new PacketDecoder(); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); InetSocketAddress sender = new InetSocketAddress("localhost", 44035); Channel channel = Mockito.mock(Channel.class); Mockito.when(ctx.channel()).thenReturn(channel); Mockito.when(channel.remoteAddress()).thenReturn(sender); decoder.decodeMessage(ctx, new byte[] { 11 }, sender); Assert.fail();// ww w . j a v a 2 s.c o m }