@Override protected void decode(ChannelHandlerContext ctx, WebSocketFrame webSocketFrame, List<Object> list) throws Exception { ByteBuf byteBuf = webSocketFrame.content(); Proto proto = new Proto(); proto.setPacketLen(byteBuf.readInt()); proto.setHeaderLen(byteBuf.readShort()); proto.setVersion(byteBuf.readShort()); proto.setOperation(byteBuf.readInt()); proto.setSeqId(byteBuf.readInt()); if (proto.getPacketLen() > proto.getHeaderLen()) { byte[] bytes = new byte[proto.getPacketLen() - proto.getHeaderLen()]; byteBuf.readBytes(bytes); proto.setBody(bytes); } list.add(proto); logger.debug("decode: {}", proto); }
@Override protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception { ByteBuf buf = frame.content().order(ByteOrder.LITTLE_ENDIAN); if (buf.capacity() < 1) { // Discard empty messages return; } buf.resetReaderIndex(); int packetId = buf.readUnsignedByte(); Packet packet = reg.SERVERBOUND.constructPacket(packetId); if (packet == null) { throw new UnknownPacketException("Unknown packet ID: " + packetId); } Server.log.finest("Received packet ID " + packetId + " (" + packet.getClass().getSimpleName() + ") from " + ctx.channel().remoteAddress()); packet.readData(buf); out.add(packet); }
private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // 判断是否关闭链路的指令 if (frame instanceof CloseWebSocketFrame) { socketServerHandshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); } // 判断是否ping消息 if (frame instanceof PingWebSocketFrame) { ctx.channel().write( new PongWebSocketFrame(frame.content().retain())); return; } // 本例程仅支持文本消息,不支持二进制消息 if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format( "%s frame types not supported", frame.getClass().getName())); } // 返回应答消息 String request = ((TextWebSocketFrame) frame).text(); System.out.println("服务端收到:" + request); TextWebSocketFrame tws = new TextWebSocketFrame(new Date().toString() + ctx.channel().id() + ":" + request); // 群发 group.writeAndFlush(tws); }
@Override protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception { ByteBuf buf = frame.content().order(ByteOrder.LITTLE_ENDIAN); if (buf.capacity() < 1) { // Discard empty messages return; } buf.resetReaderIndex(); int packetId = buf.readUnsignedByte(); Packet packet = PacketRegistry.CLIENT2SERVER.constructPacket(packetId); if (packet == null) { _log.info("Unknown packet ID: " + packetId + ", user disconected!"); ctx.disconnect(); return; } Log.logDebug("Received packet ID " + packetId + " (" + packet.getClass().getSimpleName() + ") from " + ctx.channel().remoteAddress()); packet.readData(buf); out.add(packet); }
@SuppressWarnings("deprecation") @Override protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception { ByteBuf buf = frame.content().order(ByteOrder.BIG_ENDIAN); if (buf.capacity() < 1) { // Discard empty messages return; } buf.resetReaderIndex(); int packetId = buf.readUnsignedByte(); Packet packet = PacketRegistry.SERVERBOUND.constructPacket(packetId); if (packet == null) { return; } ClitherServer.log.finest("Received packet " + " (" + packet.getClass().getSimpleName() + ") from " + ctx.channel().remoteAddress()); packet.readData(buf); out.add(packet); }
private void handleFrame(Channel channel, WebSocketFrame frame, WebSocketUpgradeHandler handler, NettyWebSocket webSocket) throws Exception { if (frame instanceof CloseWebSocketFrame) { Channels.setDiscard(channel); CloseWebSocketFrame closeFrame = (CloseWebSocketFrame) frame; webSocket.onClose(closeFrame.statusCode(), closeFrame.reasonText()); } else { ByteBuf buf = frame.content(); if (buf != null && buf.readableBytes() > 0) { HttpResponseBodyPart part = config.getResponseBodyPartFactory().newResponseBodyPart(buf, frame.isFinalFragment()); handler.onBodyPartReceived(part); if (frame instanceof BinaryWebSocketFrame) { webSocket.onBinaryFragment(part); } else if (frame instanceof TextWebSocketFrame) { webSocket.onTextFragment(part); } else if (frame instanceof PingWebSocketFrame) { webSocket.onPing(part); } else if (frame instanceof PongWebSocketFrame) { webSocket.onPong(part); } } } }
private Message decodeWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return null; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return null; } if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; return parseMessage(textFrame.content()); } if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binFrame = (BinaryWebSocketFrame) frame; return parseMessage(binFrame.content()); } log.warn("Message format error: " + frame); return null; }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } if (frame instanceof BinaryWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } }
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("client channelRead0 "+ctx); Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); } if(msg instanceof WebSocketFrame){ WebSocketFrame frame = (WebSocketFrame)msg; if(frame instanceof BinaryWebSocketFrame){ handleWebSocketFrame(ctx, frame); } return; } return; }
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("client channelRead0 "+ctx); Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); } if(msg instanceof WebSocketFrame){ WebSocketFrame frame = (WebSocketFrame)msg; if(frame instanceof BinaryWebSocketFrame){ handleWebSocketFrame(ctx, frame); } return; } sendRealTimeMessageTest(ctx); return; }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { addTraceForFrame(frame, "close"); handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { addTraceForFrame(frame, "ping"); ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } // todo [om] think about BinaryWebsocketFrame handleTextWebSocketFrameInternal((TextWebSocketFrame) frame, ctx); }
@Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) { // ping and pong frames already handled if (frame instanceof TextWebSocketFrame) { // Send the uppercase string back. String request = ((TextWebSocketFrame) frame).text(); handler.onText(new WsChannelImpl(ctx.channel()), request); } else { String message = "unsupported frame type: " + frame.getClass().getName(); throw new UnsupportedOperationException(message); } }
@Override protected void channelRead0(ChannelHandlerContext context, Object message) throws Exception { final Channel channel = context.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(channel, (FullHttpResponse) message); channel.pipeline().addBefore(HANDLER_NAME, "websocket-frame-aggregator", new WebSocketFrameAggregator(64 * 1024)); subscriber.onStart(); return; } if (message instanceof FullHttpResponse) { final FullHttpResponse response = (FullHttpResponse) message; throw new IllegalStateException( "Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } final WebSocketFrame frame = (WebSocketFrame) message; if (frame instanceof PingWebSocketFrame) { context.writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame)frame).retain().content())); } else if (frame instanceof BinaryWebSocketFrame) { final ByteBufInputStream input = new ByteBufInputStream(((BinaryWebSocketFrame)message).content()); final Envelope envelope = Envelope.ADAPTER.decode(input); subscriber.onNext(envelope); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } // Send the uppercase string back. String request = ((TextWebSocketFrame) frame).text(); System.err.printf("%s received %s%n", ctx.channel(), request); ctx.channel().write(new TextWebSocketFrame(request.toUpperCase())); }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (logger.isLoggable(Level.FINE)) { logger.fine(String.format( "Channel %s received %s", ctx.channel().hashCode(), StringUtil.simpleClassName(frame))); } if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame); } else if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content()), ctx.voidPromise()); } else if (frame instanceof TextWebSocketFrame) { ctx.write(frame, ctx.voidPromise()); } else if (frame instanceof BinaryWebSocketFrame) { ctx.write(frame, ctx.voidPromise()); } else if (frame instanceof ContinuationWebSocketFrame) { ctx.write(frame, ctx.voidPromise()); } else if (frame instanceof PongWebSocketFrame) { frame.release(); // Ignore } else { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } }
@Override public void accept(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); endpoint.releaseReferences(); endpoint.onClose(); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { endpoint.onMessage(((TextWebSocketFrame) frame).text()); return; } throw new UnsupportedOperationException(String.format("Unsupported websocket frame of type %s", frame.getClass().getName())); }
private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // 判断是否关闭链路的指令 if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } // 判断是否ping消息 if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } // 仅支持文本消息,不支持二进制消息 if (!(frame instanceof TextWebSocketFrame)) { ctx.close();//(String.format("%s frame types not supported", frame.getClass().getName())); return; } }
public void handle(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame); onClose(ctx); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } String msg = ((TextWebSocketFrame) frame).text(); onMessage(ctx, msg); }
public void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // 判断是否是关闭链路的指令 if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } // 判断是否是Ping消息 if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } //返回应答消息 String request= ((TextWebSocketFrame)frame).text(); System.out.println(String.format("%s received %s", ctx.channel(), request)); ctx.channel().write(new TextWebSocketFrame(request+" ,现在时刻:"+new Date())); }
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel channel = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(channel, (FullHttpResponse) msg); handshakeFuture.setSuccess(); eventBus.post(new Connected()); return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException( "Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; eventBus.post(new Response(textFrame.text())); } else if (frame instanceof CloseWebSocketFrame) { channel.close(); eventBus.post(new Disconnected()); } }
@Override protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception { ByteBuf buf = frame.content().order(ByteOrder.LITTLE_ENDIAN); if (buf.capacity() < 1) { // Discard empty messages return; } buf.resetReaderIndex(); int packetId = buf.readUnsignedByte(); Packet packet = PacketRegistry.SERVERBOUND.constructPacket(packetId); if (packet == null) { throw new UnknownPacketException("Unknown packet ID: " + packetId); } OgarServer.log.finest("Received packet ID " + packetId + " (" + packet.getClass().getSimpleName() + ") from " + ctx.channel().remoteAddress()); packet.readData(buf); out.add(packet); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnknownWebSocketFrameTypeException, ServerConnectorException { if (!(msg instanceof WebSocketFrame)) { logger.error("Expecting WebSocketFrame. Unknown type."); throw new UnknownWebSocketFrameTypeException("Expecting WebSocketFrame. Unknown type."); } if (msg instanceof TextWebSocketFrame) { notifyTextMessage((TextWebSocketFrame) msg); } else if (msg instanceof BinaryWebSocketFrame) { notifyBinaryMessage((BinaryWebSocketFrame) msg); } else if (msg instanceof CloseWebSocketFrame) { notifyCloseMessage((CloseWebSocketFrame) msg); } else if (msg instanceof PingWebSocketFrame) { notifyPingMessage((PingWebSocketFrame) msg); } else if (msg instanceof PongWebSocketFrame) { notifyPongMessage((PongWebSocketFrame) msg); } }
@Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { if (frame instanceof TextWebSocketFrame) { // Echos the same text String text = ((TextWebSocketFrame) frame).text(); if (PING.equals(text)) { ctx.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[]{1, 2, 3, 4}))); return; } ctx.channel().writeAndFlush(new TextWebSocketFrame(text)); } else if (frame instanceof BinaryWebSocketFrame) { ctx.channel().writeAndFlush(frame.retain()); } else if (frame instanceof CloseWebSocketFrame) { ctx.close(); } else { String message = "unsupported frame type: " + frame.getClass().getName(); throw new UnsupportedOperationException(message); } }
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { final HttpRequest httpR = (HttpRequest)msg; //handleHttpRequest(ctx, (FullHttpRequest) msg); if(WEBSOCKET_PATH.equals(httpR.uri())) { if(httpR instanceof FullHttpRequest) { handleHttpRequest(ctx, (FullHttpRequest)httpR); } } else { HttpRequestManager.getInstance().channelRead(ctx, msg); //.messageReceived(ctx, (HttpRequest)msg); } } else if (msg instanceof WebSocketFrame) { handleWebSocketFrame(ctx, (WebSocketFrame) msg); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } // Send the uppercase string back. String request = ((TextWebSocketFrame) frame).text(); if (logger.isLoggable(Level.FINE)) { logger.fine(String.format("%s received %s", ctx.channel(), request)); } ctx.channel().write(new TextWebSocketFrame(request.toUpperCase())); }
@Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { this.last = ctx; if (frame instanceof CloseWebSocketFrame) { this.log.debug("recevied close frame"); this.server.unsubscribe(this); this.handshaker.close(ctx.channel(), (CloseWebSocketFrame)frame); } else if (frame instanceof PingWebSocketFrame) { this.log.debug("recevied ping frame"); ctx.write(new PongWebSocketFrame(frame.content())); } else if (frame instanceof TextWebSocketFrame) { this.log.debug("recevied text frame"); this.handleTextWebSocketFrame(ctx, (TextWebSocketFrame)frame); } else { this.log.info("recevied unknown incompatible frame"); ctx.close(); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { _logger.debug("Handling websocket frame"); // Check for closing frame if (frame instanceof CloseWebSocketFrame) { _handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } String request = ((TextWebSocketFrame) frame).text(); _logger.debug("{} received {}", ctx.channel(), request); _messageQueue.add(frame.content().retain()); //ctx.channel().write(new TextWebSocketFrame(request.toUpperCase())); }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (logger.isLoggable(Level.FINE)) { logger.fine(String.format( "Channel %s received %s", ctx.channel().hashCode(), StringUtil.simpleClassName(frame))); } if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame); } else if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content())); } else if (frame instanceof TextWebSocketFrame) { ctx.write(frame); } else if (frame instanceof BinaryWebSocketFrame) { ctx.write(frame); } else if (frame instanceof ContinuationWebSocketFrame) { ctx.write(frame); } else if (frame instanceof PongWebSocketFrame) { frame.release(); // Ignore } else { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } if (frame instanceof BinaryWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); } }
@SuppressWarnings("unchecked") @Test public void handleInterruped() throws Exception { new MockUnit(ChannelHandlerContext.class, WebSocketServerHandshaker.class, Consumer.class, WebSocketFrame.class) .expect(unit -> { CountDownLatch ready = unit.mockConstructor(CountDownLatch.class, new Class[]{int.class }, 1); ready.await(); expectLastCall().andThrow(new InterruptedException("intentional err")); Thread thread = unit.mock(Thread.class); thread.interrupt(); unit.mockStatic(Thread.class); expect(Thread.currentThread()).andReturn(thread); }) .run(unit -> { NettyWebSocket ws = new NettyWebSocket( unit.get(ChannelHandlerContext.class), unit.get(WebSocketServerHandshaker.class), unit.get(Consumer.class)); ws.handle(unit.get(WebSocketFrame.class)); }); }
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Logger.debug("Got object: " + msg); /* if ((this.handshaker != null) && !this.handshaker.isHandshakeComplete()) { HttpResponse httpres = (HttpResponse) msg; DefaultFullHttpResponse freq = new DefaultFullHttpResponse(httpres.getProtocolVersion(), httpres.getStatus()); freq.headers().add(httpres.headers()); this.handshaker.finishHandshake(ctx.channel(), freq); Logger.info("Web Client connected!"); return; } */ if (msg instanceof HttpObject) this.handleHttpRequest(ctx, (HttpObject) msg); else if (msg instanceof WebSocketFrame) this.handleWebSocketFrame(ctx, (WebSocketFrame) msg); }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof BinaryWebSocketFrame) try { this.connection.onMessage(((BinaryWebSocketFrame) frame).content().retain()); } catch (Exception e) { logger.error("onMessage error", e); handshaker.close(ctx.channel(), new CloseWebSocketFrame(true, 0, frame.content().clear() .writeShort(1000) .writeBytes(e.getMessage().getBytes(CharsetUtil.UTF_8)) .retain())); } }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; if (req.method() == HttpMethod.GET && req.uri().startsWith(connectPath)) { final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri()); final String requestPath = queryDecoder.path(); if (log.isDebugEnabled()) log.debug("Received HTTP {} handshake request: {} from channel: {}", getTransportType().getName(), req, ctx.channel()); try { handshake(ctx, req, requestPath); } catch (Exception e) { log.error("Error during {} handshake : {}", getTransportType().getName(), e); } finally { ReferenceCountUtil.release(msg); } return; } } else if (msg instanceof WebSocketFrame && isCurrentHandlerSession(ctx)) { handleWebSocketFrame(ctx, (WebSocketFrame) msg); return; } ctx.fireChannelRead(msg); }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception { if (log.isDebugEnabled()) log.debug("Received {} WebSocketFrame: {} from channel: {}", getTransportType().getName(), msg, ctx.channel()); if (msg instanceof CloseWebSocketFrame) { sessionIdByChannel.remove(ctx.channel()); ChannelFuture f = ctx.writeAndFlush(msg); f.addListener(ChannelFutureListener.CLOSE); } else if (msg instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PongWebSocketFrame(msg.content())); } else if (msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame){ Packet packet = PacketDecoder.decodePacket(msg.content()); packet.setTransportType(getTransportType()); String sessionId = sessionIdByChannel.get(ctx.channel()); packet.setSessionId(sessionId); msg.release(); ctx.fireChannelRead(packet); } else { msg.release(); log.warn("{} frame type is not supported", msg.getClass().getName()); } }
@Override protected void decode(final ChannelHandlerContext ctx, final WebSocketFrame msg, final List<Object> out) throws Exception { if (msg instanceof BinaryWebSocketFrame) { ByteBuf content = msg.content(); // the content is passed to other handlers so they need to be retained. content.retain(); fragments.add(content); if (msg.isFinalFragment()) { if (fragments.size() == 1) { out.add(fragments.get(0)); } else { ByteBuf[] array = fragments.toArray(BYTE_BUF_TYPE); out.add(Unpooled.wrappedBuffer(array)); } fragments.clear(); } } else if (msg instanceof TextWebSocketFrame) { LOG.warn("Recieved a Websocket text frame. This was not expected. Ignoring it."); } }