io.netty.handler.codec.http.websocketx.PongWebSocketFrame Java Examples
The following examples show how to use
io.netty.handler.codec.http.websocketx.PongWebSocketFrame.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebSocketHandler.java From socketio with Apache License 2.0 | 6 votes |
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()); } }
Example #2
Source File: WebSocketService.java From netty-rest with Apache License 2.0 | 6 votes |
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); }
Example #3
Source File: AutobahnServerHandler.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
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())); } }
Example #4
Source File: WebSocketServerHandler.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
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; } }
Example #5
Source File: WebSocketServerHandler.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
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())); }
Example #6
Source File: WebsocketSinkServerHandler.java From spring-cloud-stream-app-starters with Apache License 2.0 | 6 votes |
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); }
Example #7
Source File: WebsocketServerOperations.java From reactor-netty with Apache License 2.0 | 6 votes |
@Override @SuppressWarnings("FutureReturnValueIgnored") public void onInboundNext(ChannelHandlerContext ctx, Object frame) { if (frame instanceof CloseWebSocketFrame && ((CloseWebSocketFrame) frame).isFinalFragment()) { if (log.isDebugEnabled()) { log.debug(format(channel(), "CloseWebSocketFrame detected. Closing Websocket")); } CloseWebSocketFrame close = (CloseWebSocketFrame) frame; sendCloseNow(new CloseWebSocketFrame(true, close.rsv(), close.content()), f -> terminate()); // terminate() will invoke onInboundComplete() return; } if (!this.proxyPing && frame instanceof PingWebSocketFrame) { //"FutureReturnValueIgnored" this is deliberate ctx.writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame) frame).content())); ctx.read(); return; } if (frame != LastHttpContent.EMPTY_LAST_CONTENT) { super.onInboundNext(ctx, frame); } }
Example #8
Source File: HttpWsServer.java From zbus-server with MIT License | 6 votes |
private byte[] 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()); } logger.warn("Message format error: " + frame); return null; }
Example #9
Source File: WebSocketServerHandler.java From tools-journey with Apache License 2.0 | 6 votes |
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()); } }
Example #10
Source File: WebsocketHandler.java From carbon-apimgt with Apache License 2.0 | 6 votes |
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if ((msg instanceof CloseWebSocketFrame) || (msg instanceof PongWebSocketFrame)) { //if the inbound frame is a closed frame, throttling, analytics will not be published. outboundHandler().write(ctx, msg, promise); } else if (msg instanceof WebSocketFrame) { if (isAllowed(ctx, (WebSocketFrame) msg)) { outboundHandler().write(ctx, msg, promise); // publish analytics events if analytics is enabled if (APIUtil.isAnalyticsEnabled()) { String clientIp = getClientIp(ctx); inboundHandler().publishRequestEvent(clientIp, true); } } else { if (log.isDebugEnabled()){ log.debug("Outbound Websocket frame is throttled. " + ctx.channel().toString()); } } } else { outboundHandler().write(ctx, msg, promise); } }
Example #11
Source File: NettyWebSocketSessionSupport.java From java-technology-stack with MIT License | 6 votes |
protected WebSocketFrame toFrame(WebSocketMessage message) { ByteBuf byteBuf = NettyDataBufferFactory.toByteBuf(message.getPayload()); if (WebSocketMessage.Type.TEXT.equals(message.getType())) { return new TextWebSocketFrame(byteBuf); } else if (WebSocketMessage.Type.BINARY.equals(message.getType())) { return new BinaryWebSocketFrame(byteBuf); } else if (WebSocketMessage.Type.PING.equals(message.getType())) { return new PingWebSocketFrame(byteBuf); } else if (WebSocketMessage.Type.PONG.equals(message.getType())) { return new PongWebSocketFrame(byteBuf); } else { throw new IllegalArgumentException("Unexpected message type: " + message.getType()); } }
Example #12
Source File: AutobahnServerHandler.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
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 || frame instanceof BinaryWebSocketFrame || 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())); } }
Example #13
Source File: WebSocketServerHandler.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
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()); } }
Example #14
Source File: BaseWebSocketServerHandler.java From arcusplatform with Apache License 2.0 | 6 votes |
protected void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof PingWebSocketFrame) { if (logger.isTraceEnabled()) { logger.trace("Ping with payload [{}]", ByteBufUtil.hexDump(frame.content())); } PongWebSocketFrame pong = new PongWebSocketFrame(frame.content().retain()); ctx.writeAndFlush(pong); } else if (frame instanceof PongWebSocketFrame) { PingPong pingPongSession = PingPong.get(ctx.channel()); if (pingPongSession != null) { pingPongSession.recordPong(); } } else { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } }
Example #15
Source File: LogUtil.java From micro-integrator with Apache License 2.0 | 6 votes |
/** * Print {@link WebSocketFrame} information. * * @param log {@link Log} object of the relevant class * @param frame {@link WebSocketFrame} frame * @param channelContextId {@link ChannelHandlerContext} context id as a String * @param customMsg Log message which needs to be appended to the frame information, * if it is not required provide null * @param isInbound true if the frame is inbound, false if it is outbound */ private static void printWebSocketFrame( Log log, WebSocketFrame frame, String channelContextId, String customMsg, boolean isInbound) { String logStatement = getDirectionString(isInbound) + channelContextId; if (frame instanceof PingWebSocketFrame) { logStatement += " Ping frame"; } else if (frame instanceof PongWebSocketFrame) { logStatement += " Pong frame"; } else if (frame instanceof CloseWebSocketFrame) { logStatement += " Close frame"; } else if (frame instanceof BinaryWebSocketFrame) { logStatement += " Binary frame"; } else if (frame instanceof TextWebSocketFrame) { logStatement += " " + ((TextWebSocketFrame) frame).text(); } //specifically for logging close websocket frames with error status if (customMsg != null) { logStatement += " " + customMsg; } log.debug(logStatement); }
Example #16
Source File: FrameHandler.java From quarkus-http with Apache License 2.0 | 6 votes |
private void onPongMessage(final PongWebSocketFrame frame) { if (session.isSessionClosed()) { //to bad, the channel has already been closed //we just ignore messages that are received after we have closed, as the endpoint is no longer in a valid state to deal with them //this this should only happen if a message was on the wire when we called close() return; } final HandlerWrapper handler = getHandler(FrameType.PONG); if (handler != null) { final PongMessage message = DefaultPongMessage.create(Unpooled.copiedBuffer(frame.content()).nioBuffer()); session.getContainer().invokeEndpointMethod(executor, new Runnable() { @Override public void run() { try { ((MessageHandler.Whole) handler.getHandler()).onMessage(message); } catch (Exception e) { invokeOnError(e); } } }); } }
Example #17
Source File: FrameHandler.java From quarkus-http with Apache License 2.0 | 6 votes |
private void processFrame(WebSocketFrame msg) throws IOException { if (msg instanceof CloseWebSocketFrame) { onCloseFrame((CloseWebSocketFrame) msg); } else if (msg instanceof PongWebSocketFrame) { onPongMessage((PongWebSocketFrame) msg); } else if (msg instanceof PingWebSocketFrame) { byte[] data = new byte[msg.content().readableBytes()]; msg.content().readBytes(data); session.getAsyncRemote().sendPong(ByteBuffer.wrap(data)); } else if (msg instanceof TextWebSocketFrame) { onText(msg, ((TextWebSocketFrame) msg).text()); } else if (msg instanceof BinaryWebSocketFrame) { onBinary(msg); } else if (msg instanceof ContinuationWebSocketFrame) { if (expectedContinuation == FrameType.BYTE) { onBinary(msg); } else if (expectedContinuation == FrameType.TEXT) { onText(msg, ((ContinuationWebSocketFrame) msg).text()); } } }
Example #18
Source File: NettyWebSocketSessionSupport.java From spring-analysis-note with MIT License | 6 votes |
protected WebSocketFrame toFrame(WebSocketMessage message) { ByteBuf byteBuf = NettyDataBufferFactory.toByteBuf(message.getPayload()); if (WebSocketMessage.Type.TEXT.equals(message.getType())) { return new TextWebSocketFrame(byteBuf); } else if (WebSocketMessage.Type.BINARY.equals(message.getType())) { return new BinaryWebSocketFrame(byteBuf); } else if (WebSocketMessage.Type.PING.equals(message.getType())) { return new PingWebSocketFrame(byteBuf); } else if (WebSocketMessage.Type.PONG.equals(message.getType())) { return new PongWebSocketFrame(byteBuf); } else { throw new IllegalArgumentException("Unexpected message type: " + message.getType()); } }
Example #19
Source File: WebsocketLogUtil.java From micro-integrator with Apache License 2.0 | 6 votes |
/** * Print {@link WebSocketFrame} information. * * @param log {@link Logger} object of the relevant class * @param frame {@link WebSocketFrame} frame * @param channelContextId {@link ChannelHandlerContext} context id as a String * @param customMsg Log message which needs to be appended to the frame information, * if it is not required provide null * @param isInbound true if the frame is inbound, false if it is outbound */ private static void printWebSocketFrame(Logger log, WebSocketFrame frame, String channelContextId, String customMsg, boolean isInbound) { String logStatement = getDirectionString(isInbound) + channelContextId; if (frame instanceof PingWebSocketFrame) { logStatement += " Ping frame"; } else if (frame instanceof PongWebSocketFrame) { logStatement += " Pong frame"; } else if (frame instanceof CloseWebSocketFrame) { logStatement += " Close frame"; } else if (frame instanceof BinaryWebSocketFrame) { logStatement += " Binary frame"; } else if (frame instanceof TextWebSocketFrame) { logStatement += " " + ((TextWebSocketFrame) frame).text(); } //specifically for logging close websocket frames with error status if (customMsg != null) { logStatement += " " + customMsg; } log.debug(logStatement); }
Example #20
Source File: JsrWebSocketServerTest.java From quarkus-http with Apache License 2.0 | 6 votes |
@org.junit.Test @Ignore("UT3 - P4") public void testPingPong() throws Exception { final byte[] payload = "payload".getBytes(); final AtomicReference<Throwable> cause = new AtomicReference<>(); final AtomicBoolean connected = new AtomicBoolean(false); final CompletableFuture<?> latch = new CompletableFuture<>(); class TestEndPoint extends Endpoint { @Override public void onOpen(final Session session, EndpointConfig config) { connected.set(true); } } ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getEventLoopSupplier(), Collections.EMPTY_LIST, false, false); builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build()); deployServlet(builder); WebSocketTestClient client = new WebSocketTestClient(new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/")); client.connect(); client.send(new PingWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(PongWebSocketFrame.class, payload, latch)); latch.get(10, TimeUnit.SECONDS); Assert.assertNull(cause.get()); client.destroy(); }
Example #21
Source File: WebSocketUpgradeHandler.java From selenium with Apache License 2.0 | 6 votes |
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame); // Pass on to the rest of the channel ctx.fireChannelRead(frame); } else if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content())); } else if (frame instanceof ContinuationWebSocketFrame) { ctx.write(frame); } else if (frame instanceof PongWebSocketFrame) { frame.release(); } else if (frame instanceof BinaryWebSocketFrame || frame instanceof TextWebSocketFrame) { // Allow the rest of the pipeline to deal with this. ctx.fireChannelRead(frame); } else { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } }
Example #22
Source File: HttpServerHandler.java From ext-opensource-netty with Mozilla Public License 2.0 | 6 votes |
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { if (webSocketEvent != null) { webSocketEvent.onMessageStringEvent(baseServer, new WebSocketSession(ctx.channel()), ((TextWebSocketFrame) frame).text()); } return; } if (frame instanceof BinaryWebSocketFrame) { if (webSocketEvent != null) { webSocketEvent.onMessageBinaryEvent(baseServer, new WebSocketSession(ctx.channel()), ((BinaryWebSocketFrame)frame).content()); } } }
Example #23
Source File: WebsocketPingPongIntegrationTest.java From rsocket-java with Apache License 2.0 | 5 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof PongWebSocketFrame) { pong.onNext(((PongWebSocketFrame) msg).content().toString(StandardCharsets.UTF_8)); ReferenceCountUtil.safeRelease(msg); ctx.read(); } else { super.channelRead(ctx, msg); } }
Example #24
Source File: BaseWebsocketServerTransport.java From rsocket-java with Apache License 2.0 | 5 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof PongWebSocketFrame) { logger.debug("received WebSocket Pong Frame"); ReferenceCountUtil.safeRelease(msg); ctx.read(); } else { ctx.fireChannelRead(msg); } }
Example #25
Source File: WebSocketServerHandler.java From activemq-artemis with Apache License 2.0 | 5 votes |
private boolean handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { this.handshaker.close(ctx.channel(), ((CloseWebSocketFrame) frame).retain()); return false; } else if (frame instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PongWebSocketFrame(frame.content().retain())); return false; } else if (!(frame instanceof TextWebSocketFrame) && !(frame instanceof BinaryWebSocketFrame) && !(frame instanceof ContinuationWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } return true; }
Example #26
Source File: WebSocketClientHandler.java From tinkerpop with Apache License 2.0 | 5 votes |
@Override protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception { final Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { // web socket client connected handshaker.finishHandshake(ch, (FullHttpResponse) msg); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { final FullHttpResponse response = (FullHttpResponse) msg; throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } // a close frame doesn't mean much here. errors raised from closed channels will mark the host as dead final WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { ctx.fireChannelRead(frame.retain(2)); } else if (frame instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PongWebSocketFrame()); }else if (frame instanceof PongWebSocketFrame) { logger.debug("Received response from keep-alive request"); } else if (frame instanceof BinaryWebSocketFrame) { ctx.fireChannelRead(frame.retain(2)); } else if (frame instanceof CloseWebSocketFrame) ch.close(); }
Example #27
Source File: WebSocketClientHandler.java From rsocket-java with Apache License 2.0 | 5 votes |
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { try { handshaker.finishHandshake(ch, (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); } catch (WebSocketHandshakeException e) { System.out.println("WebSocket Client failed to connect"); handshakeFuture.setFailure(e); } 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; System.out.println("WebSocket Client received message: " + textFrame.text()); } 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(); } }
Example #28
Source File: WebSocketClientHandler.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel(); 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; System.out.println("WebSocket Client received message: " + textFrame.text()); } 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(); } }
Example #29
Source File: StockTickerServerHandler.java From khs-stockticker with Apache License 2.0 | 5 votes |
protected void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { logger.debug("Received incoming frame [{}]", frame.getClass().getName()); // Check for closing frame if (frame instanceof CloseWebSocketFrame) { if (frameBuffer != null) { handleMessageCompleted(ctx, frameBuffer.toString()); } handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof PongWebSocketFrame) { logger.info("Pong frame received"); return; } if (frame instanceof TextWebSocketFrame) { frameBuffer = new StringBuilder(); frameBuffer.append(((TextWebSocketFrame)frame).text()); } else if (frame instanceof ContinuationWebSocketFrame) { if (frameBuffer != null) { frameBuffer.append(((ContinuationWebSocketFrame)frame).text()); } else { logger.warn("Continuation frame received without initial frame."); } } else { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } // Check if Text or Continuation Frame is final fragment and handle if needed. if (frame.isFinalFragment()) { handleMessageCompleted(ctx, frameBuffer.toString()); frameBuffer = null; } }
Example #30
Source File: WampServerWebsocketHandler.java From GreenBits with GNU General Public License v3.0 | 5 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // Discard messages when we are not reading if (readState != ReadState.Reading) { ReferenceCountUtil.release(msg); return; } // We might receive http requests here when the whe clients sends something after the upgrade // request but we have not fully sent out the response and the http codec is still installed. // However that would be an error. if (msg instanceof FullHttpRequest) { ((FullHttpRequest) msg).release(); WampServerWebsocketHandler.sendBadRequestAndClose(ctx, null); return; } if (msg instanceof PingWebSocketFrame) { // Respond to Pings with Pongs try { ctx.writeAndFlush(new PongWebSocketFrame()); } finally { ((PingWebSocketFrame) msg).release(); } } else if (msg instanceof CloseWebSocketFrame) { // Echo the close and close the connection readState = ReadState.Closed; ctx.writeAndFlush(msg).addListener(ChannelFutureListener.CLOSE); } else { ctx.fireChannelRead(msg); } }