@Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { if (frame instanceof TextWebSocketFrame) { String text = ((TextWebSocketFrame) frame).text(); Connection connection = connectionManager.get(ctx.channel()); Packet packet = PacketDecoder.decodeFrame(text); LOGGER.debug("channelRead conn={}, packet={}", ctx.channel(), connection.getSessionContext(), packet); receiver.onReceive(packet, connection); } else { String message = "unsupported frame type: " + frame.getClass().getName(); throw new UnsupportedOperationException(message); } }
final String text = tf.text(); logger.debug("received test frame: {}", text); if (text != null && text.startsWith("ECHO ")) { //echo protocol
@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()); String textReceived = textFrame.text(); callback.call(textReceived); } else if (frame instanceof CloseWebSocketFrame) { isConnected = false; LOGGER.debug("WebSocket Client received closing"); ch.close(); } }
private void handleWebSocketFrame(final ChannelHandlerContext ctx, WebSocketFrame frame) throws JsonProcessingException { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { clientRegistry.remove(ctx); } }); } else if (frame instanceof TextWebSocketFrame) { try { HttpRequest httpRequest = httpRequestSerializer.deserialize(((TextWebSocketFrame) frame).text()); clientRegistry.put(ctx, httpRequest); sendUpdate(httpRequest, ctx); } catch (IllegalArgumentException iae) { sendMessage(ctx, ImmutableMap.<String, Object>of("error", iae.getMessage())); } } else if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); } else { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } }
/** * Only supported TextWebSocketFrame * * @param ctx * @param frame */ private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { this.handler.onDisConnect(this.context); this.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("unsupported frame type: " + frame.getClass().getName()); } this.context.setReqText(((TextWebSocketFrame) frame).text()); this.handler.onText(this.context); }
public void handle(final Object msg) { ready(); if (msg instanceof TextWebSocketFrame) { onTextCallback.accept(((TextWebSocketFrame) msg).text()); } else if (msg instanceof BinaryWebSocketFrame) { onBinaryCallback.accept(((BinaryWebSocketFrame) msg).content().nioBuffer()); } else if (msg instanceof CloseWebSocketFrame) { CloseWebSocketFrame closeFrame = ((CloseWebSocketFrame) msg).retain(); int statusCode = closeFrame.statusCode(); onCloseCallback.accept(statusCode == -1 ? WebSocket.NORMAL.code() : statusCode, Optional.ofNullable(closeFrame.reasonText())); handshaker.close(ctx.channel(), closeFrame).addListener(CLOSE); } else if (msg instanceof Throwable) { onErrorCallback.accept((Throwable) msg); } }
/** * Only supported TextWebSocketFrame * * @param ctx * @param frame */ private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { this.handler.onDisConnect(this.context); this.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("unsupported frame type: " + frame.getClass().getName()); } this.context.setReqText(((TextWebSocketFrame) frame).text()); this.handler.onText(this.context); }
final String text = tf.text(); logger.debug("received test frame: {}", text); if (text != null && text.startsWith("ECHO ")) { //echo protocol
void receivedTextWebSocketFrame(TextWebSocketFrame textWebSocketFrame) { try { availableWebSocketCallbackRegistrations.tryAcquire(); Object deserializedMessage = webSocketMessageSerializer.deserialize(textWebSocketFrame.text()); if (deserializedMessage instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) deserializedMessage; String webSocketCorrelationId = httpRequest.getFirstHeader(WEB_SOCKET_CORRELATION_ID_HEADER_NAME); if (expectationCallback != null) { try { T result = expectationCallback.handle(httpRequest); result.withHeader(WEB_SOCKET_CORRELATION_ID_HEADER_NAME, webSocketCorrelationId); channel.writeAndFlush(new TextWebSocketFrame(webSocketMessageSerializer.serialize(result))); } catch (Throwable throwable) { mockServerLogger.error("Exception thrown while handling callback", throwable); channel.writeAndFlush(new TextWebSocketFrame(webSocketMessageSerializer.serialize( new WebSocketErrorDTO() .setMessage(throwable.getMessage()) .setWebSocketCorrelationId(webSocketCorrelationId) ))); } } } else if (!(deserializedMessage instanceof WebSocketClientIdDTO)) { throw new WebSocketException("Unsupported web socket message " + deserializedMessage); } } catch (Exception e) { throw new WebSocketException("Exception while receiving web socket message", e); } finally { availableWebSocketCallbackRegistrations.release(); } }
void receivedTextWebSocketFrame(TextWebSocketFrame textWebSocketFrame) { try { Object deserializedMessage = webSocketMessageSerializer.deserialize(textWebSocketFrame.text()); if (deserializedMessage instanceof HttpResponse) { HttpResponse httpResponse = (HttpResponse) deserializedMessage; throw new WebSocketException("Exception while receiving web socket message" + textWebSocketFrame.text(), e);
@Override protected void decode(final ChannelHandlerContext channelHandlerContext, final TextWebSocketFrame frame, final List<Object> objects) throws Exception { try { // the default serializer must be a MessageTextSerializer instance to be compatible with this decoder final MessageTextSerializer serializer = (MessageTextSerializer) select("application/json", ServerSerializers.DEFAULT_SERIALIZER); // it's important to re-initialize these channel attributes as they apply globally to the channel. in // other words, the next request to this channel might not come with the same configuration and mixed // state can carry through from one request to the next channelHandlerContext.channel().attr(StateKey.SESSION).set(null); channelHandlerContext.channel().attr(StateKey.SERIALIZER).set(serializer); channelHandlerContext.channel().attr(StateKey.USE_BINARY).set(false); objects.add(serializer.deserializeRequest(frame.text())); } catch (SerializationException se) { objects.add(RequestMessage.INVALID); } }
@Override protected void decode(final ChannelHandlerContext channelHandlerContext, final WebSocketFrame webSocketFrame, final List<Object> objects) throws Exception { try { if (webSocketFrame instanceof BinaryWebSocketFrame) { final BinaryWebSocketFrame tf = (BinaryWebSocketFrame) webSocketFrame; objects.add(serializer.deserializeResponse(tf.content())); } else if (webSocketFrame instanceof TextWebSocketFrame){ final TextWebSocketFrame tf = (TextWebSocketFrame) webSocketFrame; final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer; objects.add(textSerializer.deserializeResponse(tf.text())); } else { throw new RuntimeException(String.format("WebSocket channel does not handle this type of message: %s", webSocketFrame.getClass().getName())); } } finally { ReferenceCountUtil.release(webSocketFrame); } } }
@SuppressWarnings("unchecked") final EJValue val = JSONDecoder.decode(((TextWebSocketFrame) frame).text());
private void addTraceForFrame(WebSocketFrame frame, String type) { Map<String, Object> trace = new LinkedHashMap<>(); trace.put("type", type); trace.put("direction", "in"); if (frame instanceof TextWebSocketFrame) { trace.put("payload", ((TextWebSocketFrame) frame).text()); } if (traceEnabled) { websocketTraceRepository.add(trace); } }
private void handleTextWebSocketFrameInternal(TextWebSocketFrame frame, ChannelHandlerContext ctx) { if (logger.isTraceEnabled()) { logger.trace(String.format("%s received %s", ctx.channel(), frame.text())); } addTraceForFrame(frame, "text"); ctx.channel().write(new TextWebSocketFrame("Echo: " + frame.text())); }
@Override public void channelRead0(final ChannelHandlerContext ctx, final TextWebSocketFrame message) throws Exception { this.getSession().ifPresent(s -> this.handler.processMessages(s, message.text())); } }
@Override public ChannelFuture write(Object message) { if(message instanceof TextWebSocketFrame) { writer.write(((TextWebSocketFrame)message).text()); } else { throw new IllegalStateException("Expected a TextWebSocketFrame but got " + message); } return null; }
@Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception { UserInfo userInfo = UserInfoManager.getUserInfo(ctx.channel()); if (userInfo != null && userInfo.isAuth()) { JSONObject json = JSONObject.parseObject(frame.text()); // 广播返回用户发送的消息文本 UserInfoManager.broadcastMess(userInfo.getUserId(), userInfo.getNick(), json.getString("mess")); } }
private void notifyTextMessage(TextWebSocketFrame textWebSocketFrame) throws ServerConnectorException { String text = textWebSocketFrame.text(); boolean isFinalFragment = textWebSocketFrame.isFinalFragment(); WebSocketMessageImpl webSocketTextMessage = new WebSocketTextMessageImpl(text, isFinalFragment); webSocketTextMessage = setupCommonProperties(webSocketTextMessage); connectorFuture.notifyWSListener((WebSocketTextMessage) webSocketTextMessage); }
private void notifyTextMessage(TextWebSocketFrame textWebSocketFrame, ChannelHandlerContext ctx) throws ServerConnectorException { String text = textWebSocketFrame.text(); boolean isFinalFragment = textWebSocketFrame.isFinalFragment(); WebSocketMessageImpl webSocketTextMessage = new WebSocketTextMessageImpl(text, isFinalFragment); webSocketTextMessage = setupCommonProperties(webSocketTextMessage, ctx); connectorListener.onMessage((WebSocketTextMessage) webSocketTextMessage); }