io.netty.handler.codec.http.websocketx.PingWebSocketFrame Java Examples

The following examples show how to use io.netty.handler.codec.http.websocketx.PingWebSocketFrame. 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: WebSocketServerHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: WebsocketServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: HttpWsServer.java    From zbus-server with MIT License 6 votes vote down vote up
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 #4
Source File: Subscription.java    From timely with Apache License 2.0 6 votes vote down vote up
public Subscription(String subscriptionId, String sessionId, DataStore store, DataStoreCache cache,
        ChannelHandlerContext ctx, Configuration conf) {
    this.subscriptionId = subscriptionId;
    this.sessionId = sessionId;
    this.store = store;
    this.cache = cache;
    this.ctx = ctx;
    this.lag = conf.getWebsocket().getSubscriptionLag();
    this.scannerBatchSize = conf.getWebsocket().getScannerBatchSize();
    this.flushIntervalSeconds = conf.getWebsocket().getFlushIntervalSeconds();
    this.scannerReadAhead = conf.getWebsocket().getScannerReadAhead();
    this.subscriptionBatchSize = conf.getWebsocket().getSubscriptionBatchSize();
    // send a websocket ping at half the timeout interval.
    int rate = conf.getWebsocket().getTimeout() / 2;
    this.ping = this.ctx.executor().scheduleAtFixedRate(() -> {
        LOG.trace("[{}] Sending ping on channel {}", subscriptionId, ctx.channel());
        ctx.writeAndFlush(new PingWebSocketFrame());
        cleanupCompletedMetrics();
    }, rate, rate, TimeUnit.SECONDS);
}
 
Example #5
Source File: WebsocketSinkServerHandler.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: WebSocketServerHandler.java    From tools-journey with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: WebSocketServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: WebSocketServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: NettyWebSocketSessionSupport.java    From java-technology-stack with MIT License 6 votes vote down vote up
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 #10
Source File: AutobahnServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: AutobahnServerHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: WebSocketService.java    From netty-rest with Apache License 2.0 6 votes vote down vote up
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 #13
Source File: BaseWebSocketServerHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: WebSocketHandler.java    From socketio with Apache License 2.0 6 votes vote down vote up
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 #15
Source File: WebsocketLogUtil.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #16
Source File: JsrWebSocketServerTest.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@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 #17
Source File: LogUtil.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #18
Source File: WebSocketUpgradeHandler.java    From selenium with Apache License 2.0 6 votes vote down vote up
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 #19
Source File: HttpServerHandler.java    From ext-opensource-netty with Mozilla Public License 2.0 6 votes vote down vote up
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 #20
Source File: FrameHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
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 #21
Source File: NettyWebSocketSessionSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
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 #22
Source File: WampServerWebsocketHandler.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@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);
    }
}
 
Example #23
Source File: WebsocketTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue663_2() {
	FluxIdentityProcessor<WebSocketFrame> incomingData = Processors.more().multicastNoBackpressure();

	httpServer =
			HttpServer.create()
			          .port(0)
			          .handle((req, resp) ->
			              resp.sendWebsocket((i, o) ->
			                  o.sendObject(Flux.just(new PingWebSocketFrame(), new CloseWebSocketFrame())
			                   .delayElements(Duration.ofMillis(100)))
			                   .then(i.receiveFrames()
			                          .subscribeWith(incomingData)
			                          .then())))
			          .wiretap(true)
			          .bindNow();

	HttpClient.create()
	          .port(httpServer.port())
	          .wiretap(true)
	          .websocket(WebsocketClientSpec.builder().handlePing(true).build())
	          .uri("/")
	          .handle((in, out) -> in.receiveFrames())
	          .subscribe();

	StepVerifier.create(incomingData)
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));
}
 
Example #24
Source File: WebsocketTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue663_3() {
	FluxIdentityProcessor<WebSocketFrame> incomingData = Processors.more().multicastNoBackpressure();

	httpServer =
			HttpServer.create()
			          .port(0)
			          .handle((req, resp) -> resp.sendWebsocket((i, o) -> i.receiveFrames().then()))
			          .wiretap(true)
			          .bindNow();

	HttpClient.create()
	          .port(httpServer.port())
	          .wiretap(true)
	          .websocket()
	          .uri("/")
	          .handle((in, out) ->
	              out.sendObject(Flux.just(new PingWebSocketFrame(), new CloseWebSocketFrame())
	                                 .delayElements(Duration.ofMillis(100)))
	                 .then(in.receiveFrames()
	                         .subscribeWith(incomingData)
	                         .then()))
	          .subscribe();

	StepVerifier.create(incomingData)
	            .expectNext(new PongWebSocketFrame())
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));
}
 
Example #25
Source File: WebsocketTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue663_4() {
	FluxIdentityProcessor<WebSocketFrame> incomingData = Processors.more().multicastNoBackpressure();

	httpServer =
			HttpServer.create()
			          .port(0)
			          .handle((req, resp) -> resp.sendWebsocket((i, o) -> i.receiveFrames().then(),
			                  WebsocketServerSpec.builder().handlePing(true).build()))
			          .wiretap(true)
			          .bindNow();

	HttpClient.create()
	          .port(httpServer.port())
	          .wiretap(true)
	          .websocket()
	          .uri("/")
	          .handle((in, out) ->
	              out.sendObject(Flux.just(new PingWebSocketFrame(), new CloseWebSocketFrame())
	                                 .delayElements(Duration.ofMillis(100)))
	                 .then(in.receiveFrames()
	                         .subscribeWith(incomingData)
	                         .then()))
	          .subscribe();

	StepVerifier.create(incomingData)
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));
}
 
Example #26
Source File: WebSocketTestClient.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Send a ping message to the server.
 *
 * @param buf content of the ping message to be sent.
 */
public void sendPing(ByteBuffer buf) throws IOException {
    if (channel == null) {
        logger.error("Channel is null. Cannot send text.");
        throw new IllegalArgumentException("Cannot find the channel to write");
    }
    channel.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(buf)));
}
 
Example #27
Source File: StockTickerServerHandler.java    From khs-stockticker with Apache License 2.0 5 votes vote down vote up
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 #28
Source File: WampServerWebsocketHandler.java    From jawampa with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #29
Source File: WebSocketClientHandler.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@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 #30
Source File: AbstractWebSocketHandler.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        } else if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
            return;
        } else if (!(frame instanceof TextWebSocketFrame)) {
            throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
        }

        exec(ctx, frame);
    }