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

The following examples show how to use io.netty.handler.codec.http.websocketx.CloseWebSocketFrame. 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: TextWebSocketFrameHandler.java    From leo-im-server with Apache License 2.0 6 votes vote down vote up
/**
 * 处理WebSocket请求
 * 
 * @param ctx
 * @param frame
 */
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        ctx.close();
        return;
    }
    // 没有使用WebSocketServerProtocolHandler,所以不会接收到PingWebSocketFrame。
    // if (frame instanceof PingWebSocketFrame) {
    // ctx.writeAndFlush(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("收到客户端发送的数据:" + request);
    // 回复心跳
    if (request.length() == 0) {
        ctx.writeAndFlush(new TextWebSocketFrame(""));
        return;
    }
    this.handleMessage(ctx.channel(), request);
}
 
Example #2
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 #3
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 #4
Source File: WebsocketClientOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
void sendCloseNow(@Nullable CloseWebSocketFrame frame) {
	if (frame != null && !frame.isFinalFragment()) {
		//"FutureReturnValueIgnored" this is deliberate
		channel().writeAndFlush(frame);
		return;
	}
	if (CLOSE_SENT.getAndSet(this, 1) == 0) {
		if (frame != null) {
			onCloseState.onNext(new WebSocketCloseStatus(frame.statusCode(), frame.reasonText()));
			channel().writeAndFlush(frame)
			         .addListener(ChannelFutureListener.CLOSE);
		} else {
			onCloseState.onNext(new WebSocketCloseStatus(-1, ""));
			channel().writeAndFlush(new CloseWebSocketFrame())
			         .addListener(ChannelFutureListener.CLOSE);
		}
	}
	else if (frame != null) {
		frame.release();
	}
}
 
Example #5
Source File: WebsocketServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
void sendCloseNow(@Nullable CloseWebSocketFrame frame, ChannelFutureListener listener) {
	if (frame != null && !frame.isFinalFragment()) {
		//"FutureReturnValueIgnored" this is deliberate
		channel().writeAndFlush(frame);
		return;
	}
	if (CLOSE_SENT.getAndSet(this, 1) == 0) {
		if (frame != null) {
			onCloseState.onNext(new WebSocketCloseStatus(frame.statusCode(), frame.reasonText()));
			channel().writeAndFlush(frame)
			         .addListener(listener);
		} else {
			onCloseState.onNext(new WebSocketCloseStatus(-1, ""));
			channel().writeAndFlush(new CloseWebSocketFrame())
			         .addListener(listener);
		}
	}
	else if (frame != null) {
		frame.release();
	}
}
 
Example #6
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 #7
Source File: WebsocketServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
Mono<Void> sendClose(CloseWebSocketFrame frame) {
	if (CLOSE_SENT.get(this) == 0) {
		//commented for now as we assume the close is always scheduled (deferFuture runs)
		//onTerminate().subscribe(null, null, () -> ReactorNetty.safeRelease(frame));
		return FutureMono.deferFuture(() -> {
			if (CLOSE_SENT.getAndSet(this, 1) == 0) {
				discard();
				onCloseState.onNext(new WebSocketCloseStatus(frame.statusCode(), frame.reasonText()));
				return channel().writeAndFlush(frame)
				                .addListener(ChannelFutureListener.CLOSE);
			}
			frame.release();
			return channel().newSucceededFuture();
		}).doOnCancel(() -> ReactorNetty.safeRelease(frame));
	}
	frame.release();
	return Mono.empty();
}
 
Example #8
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 #9
Source File: WebsocketTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseWebSocketFrameSentByClient() {
	httpServer =
			HttpServer.create()
			          .port(0)
			          .handle((req, res) ->
			                  res.sendWebsocket((in, out) -> out.sendString(Mono.just("echo"))
			                                                    .sendObject(new CloseWebSocketFrame())))
			          .wiretap(true)
			          .bindNow();

	Mono<Void> response =
			HttpClient.create()
			          .port(httpServer.port())
			          .websocket()
			          .uri("/")
			          .handle((in, out) -> out.sendObject(in.receiveFrames()
			                                                .doOnNext(WebSocketFrame::retain)
			                                                .then()))
			          .next();

	StepVerifier.create(response)
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));
}
 
Example #10
Source File: WebsocketTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue444() {
	doTestIssue444((in, out) ->
			out.sendObject(Flux.error(new Throwable())
			                   .onErrorResume(ex -> out.sendClose(1001, "Going Away"))
			                   .cast(WebSocketFrame.class)));
	doTestIssue444((in, out) ->
			out.send(Flux.range(0, 10)
			             .map(i -> {
			                 if (i == 5) {
			                     out.sendClose(1001, "Going Away").subscribe();
			                 }
			                 return Unpooled.copiedBuffer((i + "").getBytes(Charset.defaultCharset()));
			             })));
	doTestIssue444((in, out) ->
			out.sendObject(Flux.error(new Throwable())
			                   .onErrorResume(ex -> Flux.empty())
			                   .cast(WebSocketFrame.class))
			   .then(Mono.defer(() -> out.sendObject(
			       new CloseWebSocketFrame(1001, "Going Away")).then())));
}
 
Example #11
Source File: FrameHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
void onCloseFrame(final CloseWebSocketFrame message) {
    if (session.isSessionClosed()) {
        //we have already handled this when we sent the close frame
        return;
    }
    String reason = message.reasonText();
    int code = message.statusCode() == -1 ? CloseReason.CloseCodes.NORMAL_CLOSURE.getCode() : message.statusCode();

    session.getContainer().invokeEndpointMethod(executor, new Runnable() {
        @Override
        public void run() {
            try {
                session.closeInternal(new CloseReason(CloseReason.CloseCodes.getCloseCode(code), reason));
            } catch (IOException e) {
                invokeOnError(e);
            }
        }
    });
}
 
Example #12
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 #13
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 #14
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 #15
Source File: NettyWebSocketClient.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext context, Object message) {
  Channel channel = context.channel();
  if (message instanceof FullHttpResponse) {
    checkState(!handshaker.isHandshakeComplete());
    try {
      handshaker.finishHandshake(channel, (FullHttpResponse) message);
      delegate.onOpen();
    } catch (WebSocketHandshakeException e) {
      delegate.onError(e);
    }
  } else if (message instanceof TextWebSocketFrame) {
    delegate.onMessage(((TextWebSocketFrame) message).text());
  } else {
    checkState(message instanceof CloseWebSocketFrame);
    delegate.onClose();
  }
}
 
Example #16
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 #17
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 #18
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 #19
Source File: WebSocketRequestDecoderTest.java    From timely with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSubscriptionWithMissingSessionId() throws Exception {
    decoder = new WebSocketRequestDecoder(config.getSecurity());
// @formatter:off
    String request = "{ "+
      "\"operation\" : \"create\", " +
      "\"subscriptionId\" : \"1234\"" +
    " }";
    // @formatter:on
    TextWebSocketFrame frame = new TextWebSocketFrame();
    frame.content().writeBytes(request.getBytes(StandardCharsets.UTF_8));
    decoder.decode(ctx, frame, results);
    Assert.assertNotNull(ctx.msg);
    Assert.assertEquals(CloseWebSocketFrame.class, ctx.msg.getClass());
    Assert.assertEquals(1008, ((CloseWebSocketFrame) ctx.msg).statusCode());
    Assert.assertEquals("User must log in", ((CloseWebSocketFrame) ctx.msg).reasonText());
}
 
Example #20
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 #21
Source File: WebSocketRequestDecoderTest.java    From timely with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSubscriptionWithInvalidSessionIdAndNonAnonymousAccess() throws Exception {
    ctx.channel().attr(SubscriptionRegistry.SESSION_ID_ATTR)
            .set(URLEncoder.encode(UUID.randomUUID().toString(), StandardCharsets.UTF_8.name()));
    decoder = new WebSocketRequestDecoder(config.getSecurity());
// @formatter:off
    String request = "{ "+
      "\"operation\" : \"create\", " +
      "\"subscriptionId\" : \"1234\"" +
    " }";
    // @formatter:on
    TextWebSocketFrame frame = new TextWebSocketFrame();
    frame.content().writeBytes(request.getBytes(StandardCharsets.UTF_8));
    decoder.decode(ctx, frame, results);
    Assert.assertNotNull(ctx.msg);
    Assert.assertEquals(CloseWebSocketFrame.class, ctx.msg.getClass());
    Assert.assertEquals(1008, ((CloseWebSocketFrame) ctx.msg).statusCode());
    Assert.assertEquals("User must log in", ((CloseWebSocketFrame) ctx.msg).reasonText());
}
 
Example #22
Source File: WebsocketClientOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
Mono<Void> sendClose(CloseWebSocketFrame frame) {
	if (CLOSE_SENT.get(this) == 0) {
		//commented for now as we assume the close is always scheduled (deferFuture runs)
		//onTerminate().subscribe(null, null, () -> ReactorNetty.safeRelease(frame));
		return FutureMono.deferFuture(() -> {
			if (CLOSE_SENT.getAndSet(this, 1) == 0) {
				discard();
				onCloseState.onNext(new WebSocketCloseStatus(frame.statusCode(), frame.reasonText()));
				return channel().writeAndFlush(frame)
				                .addListener(ChannelFutureListener.CLOSE);
			}
			frame.release();
			return channel().newSucceededFuture();
		}).doOnCancel(() -> ReactorNetty.safeRelease(frame));
	}
	frame.release();
	return Mono.empty();
}
 
Example #23
Source File: WebSocketClientHandler.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: WebSocketServerHandler.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
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 #25
Source File: WampClientWebsocketHandler.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 {
    if (msg instanceof CloseWebSocketFrame) {
        //readState = ReadState.Closed;
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) msg)
                  .addListener(ChannelFutureListener.CLOSE);
    } else {
        ctx.fireChannelRead(msg);
    }
}
 
Example #26
Source File: WebsocketTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testExternalConnections_PullRequest1047() {
	String incorrectHostName = "incorrect-host.io";
	httpServer =
			HttpServer.create()
			          .port(0)
			          .handle((req, res) -> {
			              if (req.requestHeaders().get(HttpHeaderNames.HOST).contains(incorrectHostName)) {
			                  return res.status(418)
			                            .sendString(Mono.just("Incorrect Host header"));
			              }
			              return res.sendWebsocket((in, out) -> out.sendString(Mono.just("echo"))
			                                                       .sendObject(new CloseWebSocketFrame()));
			          })
			          .wiretap(true)
			          .bindNow();

	Mono<Void> response =
			HttpClient.create()
			          .port(httpServer.port())
			          .headers(h -> h.add(HttpHeaderNames.HOST, incorrectHostName))
			          .websocket()
			          .uri("/")
			          .handle((in, out) -> out.sendObject(in.receiveFrames()
			                                                .doOnNext(WebSocketFrame::retain)
			                                                .then()))
			          .next();

	StepVerifier.create(response)
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));
}
 
Example #27
Source File: WSQueryRequestHandler.java    From timely with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, QueryRequest msg) throws Exception {
    try {
        String response = JsonUtil.getObjectMapper().writeValueAsString(dataStore.query(msg));
        ctx.writeAndFlush(new TextWebSocketFrame(response));
    } catch (TimelyException e) {
        if (e.getMessage().contains("No matching tags")) {
            LOG.trace(e.getMessage());
        } else {
            LOG.error(e.getMessage(), e);
        }
        ctx.writeAndFlush(new CloseWebSocketFrame(1008, e.getMessage()));
    }
}
 
Example #28
Source File: WebsocketClientOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected void onOutboundError(Throwable err) {
	if (channel().isActive()) {
		if (log.isDebugEnabled()) {
			log.debug(format(channel(), "Outbound error happened"), err);
		}
		sendCloseNow(new CloseWebSocketFrame(1002, "Client internal error"));
	}
}
 
Example #29
Source File: WebSocketIT.java    From timely with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    LOG.info("Received msg: {}", msg);
    if (!this.handshaker.isHandshakeComplete()) {
        this.handshaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg);
        LOG.info("Client connected.");
        this.connected = true;
        this.handshakeFuture.setSuccess();
        return;
    }
    if (msg instanceof FullHttpResponse) {
        throw new IllegalStateException("Unexpected response: " + msg.toString());
    }
    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        synchronized (responses) {
            responses.add(((TextWebSocketFrame) frame).text());
        }
    } else if (frame instanceof PingWebSocketFrame) {
        LOG.info("Returning pong message");
        ctx.writeAndFlush(new PongWebSocketFrame());
    } else if (frame instanceof CloseWebSocketFrame) {
        LOG.info("Received message from server to close the channel.");
        ctx.close();
    } else {
        LOG.warn("Unhandled frame type received: " + frame.getClass());
    }
}
 
Example #30
Source File: WebSocketClientHandler.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        logger.debug("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        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;
        logger.debug("WebSocket Client received text message: " + textFrame.text());
        textReceived = textFrame.text();
    } else if (frame instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
        bufferReceived = binaryFrame.content().nioBuffer();
        logger.debug("WebSocket Client received  binary message: " + bufferReceived.toString());
    } else if (frame instanceof PongWebSocketFrame) {
        logger.debug("WebSocket Client received pong");
        PongWebSocketFrame pongFrame = (PongWebSocketFrame) frame;
        bufferReceived = pongFrame.content().nioBuffer();
    } else if (frame instanceof CloseWebSocketFrame) {
        logger.debug("WebSocket Client received closing");
        ch.close();
    }
}