private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // 判断是否关闭链路的指令 if (frame instanceof CloseWebSocketFrame) { socketServerHandshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); } // 判断是否ping消息 if (frame instanceof PingWebSocketFrame) { ctx.channel().write( new PongWebSocketFrame(frame.content().retain())); return; } // 本例程仅支持文本消息,不支持二进制消息 if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format( "%s frame types not supported", frame.getClass().getName())); } // 返回应答消息 String request = ((TextWebSocketFrame) frame).text(); System.out.println("服务端收到:" + request); TextWebSocketFrame tws = new TextWebSocketFrame(new Date().toString() + ctx.channel().id() + ":" + request); // 群发 group.writeAndFlush(tws); }
public Subscription(String subscriptionId, String sessionId, DataStore store, ChannelHandlerContext ctx, Configuration conf) { this.subscriptionId = subscriptionId; this.sessionId = sessionId; this.store = store; 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 {}", ctx.channel()); ctx.writeAndFlush(new PingWebSocketFrame()); cleanupCompletedMetrics(); }, rate, rate, TimeUnit.SECONDS); }
private void handleFrame(Channel channel, WebSocketFrame frame, WebSocketUpgradeHandler handler, NettyWebSocket webSocket) throws Exception { if (frame instanceof CloseWebSocketFrame) { Channels.setDiscard(channel); CloseWebSocketFrame closeFrame = (CloseWebSocketFrame) frame; webSocket.onClose(closeFrame.statusCode(), closeFrame.reasonText()); } else { ByteBuf buf = frame.content(); if (buf != null && buf.readableBytes() > 0) { HttpResponseBodyPart part = config.getResponseBodyPartFactory().newResponseBodyPart(buf, frame.isFinalFragment()); handler.onBodyPartReceived(part); if (frame instanceof BinaryWebSocketFrame) { webSocket.onBinaryFragment(part); } else if (frame instanceof TextWebSocketFrame) { webSocket.onTextFragment(part); } else if (frame instanceof PingWebSocketFrame) { webSocket.onPing(part); } else if (frame instanceof PongWebSocketFrame) { webSocket.onPong(part); } } } }
@Override public void onInboundNext(ChannelHandlerContext ctx, Object frame) { if (frame instanceof CloseWebSocketFrame && ((CloseWebSocketFrame) frame).isFinalFragment()) { if (log.isDebugEnabled()) { log.debug("CloseWebSocketFrame detected. Closing Websocket"); } CloseWebSocketFrame close = (CloseWebSocketFrame) frame; sendClose(new CloseWebSocketFrame(true, close.rsv(), close.content()), f -> onHandlerTerminate()); return; } if (frame instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame) frame).content())); ctx.read(); return; } super.onInboundNext(ctx, frame); }
private Message decodeWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return null; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return null; } if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; return parseMessage(textFrame.content()); } if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binFrame = (BinaryWebSocketFrame) frame; return parseMessage(binFrame.content()); } log.warn("Message format error: " + frame); return null; }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } if (frame instanceof BinaryWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { addTraceForFrame(frame, "close"); handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { addTraceForFrame(frame, "ping"); ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } // todo [om] think about BinaryWebsocketFrame handleTextWebSocketFrameInternal((TextWebSocketFrame) frame, ctx); }
@Override protected void channelRead0(ChannelHandlerContext context, Object message) throws Exception { final Channel channel = context.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(channel, (FullHttpResponse) message); channel.pipeline().addBefore(HANDLER_NAME, "websocket-frame-aggregator", new WebSocketFrameAggregator(64 * 1024)); subscriber.onStart(); return; } if (message instanceof FullHttpResponse) { final FullHttpResponse response = (FullHttpResponse) message; throw new IllegalStateException( "Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } final WebSocketFrame frame = (WebSocketFrame) message; if (frame instanceof PingWebSocketFrame) { context.writeAndFlush(new PongWebSocketFrame(((PingWebSocketFrame)frame).retain().content())); } else if (frame instanceof BinaryWebSocketFrame) { final ByteBufInputStream input = new ByteBufInputStream(((BinaryWebSocketFrame)message).content()); final Envelope envelope = Envelope.ADAPTER.decode(input); subscriber.onNext(envelope); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } // Send the uppercase string back. String request = ((TextWebSocketFrame) frame).text(); System.err.printf("%s received %s%n", ctx.channel(), request); ctx.channel().write(new TextWebSocketFrame(request.toUpperCase())); }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (logger.isLoggable(Level.FINE)) { logger.fine(String.format( "Channel %s received %s", ctx.channel().hashCode(), StringUtil.simpleClassName(frame))); } if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame); } else if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content()), ctx.voidPromise()); } else if (frame instanceof TextWebSocketFrame) { ctx.write(frame, ctx.voidPromise()); } else if (frame instanceof BinaryWebSocketFrame) { ctx.write(frame, ctx.voidPromise()); } else if (frame instanceof ContinuationWebSocketFrame) { ctx.write(frame, ctx.voidPromise()); } else if (frame instanceof PongWebSocketFrame) { frame.release(); // Ignore } else { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } }
@Override public void accept(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); endpoint.releaseReferences(); endpoint.onClose(); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { endpoint.onMessage(((TextWebSocketFrame) frame).text()); return; } throw new UnsupportedOperationException(String.format("Unsupported websocket frame of type %s", frame.getClass().getName())); }
private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // 判断是否关闭链路的指令 if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } // 判断是否ping消息 if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } // 仅支持文本消息,不支持二进制消息 if (!(frame instanceof TextWebSocketFrame)) { ctx.close();//(String.format("%s frame types not supported", frame.getClass().getName())); return; } }
public void handle(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame); onClose(ctx); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } String msg = ((TextWebSocketFrame) frame).text(); onMessage(ctx, msg); }
public void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // 判断是否是关闭链路的指令 if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } // 判断是否是Ping消息 if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } //返回应答消息 String request= ((TextWebSocketFrame)frame).text(); System.out.println(String.format("%s received %s", ctx.channel(), request)); ctx.channel().write(new TextWebSocketFrame(request+" ,现在时刻:"+new Date())); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnknownWebSocketFrameTypeException, ServerConnectorException { if (!(msg instanceof WebSocketFrame)) { logger.error("Expecting WebSocketFrame. Unknown type."); throw new UnknownWebSocketFrameTypeException("Expecting WebSocketFrame. Unknown type."); } if (msg instanceof TextWebSocketFrame) { notifyTextMessage((TextWebSocketFrame) msg); } else if (msg instanceof BinaryWebSocketFrame) { notifyBinaryMessage((BinaryWebSocketFrame) msg); } else if (msg instanceof CloseWebSocketFrame) { notifyCloseMessage((CloseWebSocketFrame) msg); } else if (msg instanceof PingWebSocketFrame) { notifyPingMessage((PingWebSocketFrame) msg); } else if (msg instanceof PongWebSocketFrame) { notifyPongMessage((PongWebSocketFrame) msg); } }
@Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { if (frame instanceof TextWebSocketFrame) { // Echos the same text String text = ((TextWebSocketFrame) frame).text(); if (PING.equals(text)) { ctx.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[]{1, 2, 3, 4}))); return; } ctx.channel().writeAndFlush(new TextWebSocketFrame(text)); } else if (frame instanceof BinaryWebSocketFrame) { ctx.channel().writeAndFlush(frame.retain()); } else if (frame instanceof CloseWebSocketFrame) { ctx.close(); } else { String message = "unsupported frame type: " + frame.getClass().getName(); throw new UnsupportedOperationException(message); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } // Send the uppercase string back. String request = ((TextWebSocketFrame) frame).text(); if (logger.isLoggable(Level.FINE)) { logger.fine(String.format("%s received %s", ctx.channel(), request)); } ctx.channel().write(new TextWebSocketFrame(request.toUpperCase())); }
@Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { this.last = ctx; if (frame instanceof CloseWebSocketFrame) { this.log.debug("recevied close frame"); this.server.unsubscribe(this); this.handshaker.close(ctx.channel(), (CloseWebSocketFrame)frame); } else if (frame instanceof PingWebSocketFrame) { this.log.debug("recevied ping frame"); ctx.write(new PongWebSocketFrame(frame.content())); } else if (frame instanceof TextWebSocketFrame) { this.log.debug("recevied text frame"); this.handleTextWebSocketFrame(ctx, (TextWebSocketFrame)frame); } else { this.log.info("recevied unknown incompatible frame"); ctx.close(); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { _logger.debug("Handling websocket frame"); // Check for closing frame if (frame instanceof CloseWebSocketFrame) { _handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } String request = ((TextWebSocketFrame) frame).text(); _logger.debug("{} received {}", ctx.channel(), request); _messageQueue.add(frame.content().retain()); //ctx.channel().write(new TextWebSocketFrame(request.toUpperCase())); }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (logger.isLoggable(Level.FINE)) { logger.fine(String.format( "Channel %s received %s", ctx.channel().hashCode(), StringUtil.simpleClassName(frame))); } if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame); } else if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content())); } else if (frame instanceof TextWebSocketFrame) { ctx.write(frame); } else if (frame instanceof BinaryWebSocketFrame) { ctx.write(frame); } else if (frame instanceof ContinuationWebSocketFrame) { ctx.write(frame); } else if (frame instanceof PongWebSocketFrame) { frame.release(); // Ignore } else { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass() .getName())); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); return; } if (frame instanceof BinaryWebSocketFrame) { // Echo the frame ctx.write(frame.retain()); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof BinaryWebSocketFrame) try { this.connection.onMessage(((BinaryWebSocketFrame) frame).content().retain()); } catch (Exception e) { logger.error("onMessage error", e); handshaker.close(ctx.channel(), new CloseWebSocketFrame(true, 0, frame.content().clear() .writeShort(1000) .writeBytes(e.getMessage().getBytes(CharsetUtil.UTF_8)) .retain())); } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception { if (log.isDebugEnabled()) log.debug("Received {} WebSocketFrame: {} from channel: {}", getTransportType().getName(), msg, ctx.channel()); if (msg instanceof CloseWebSocketFrame) { sessionIdByChannel.remove(ctx.channel()); ChannelFuture f = ctx.writeAndFlush(msg); f.addListener(ChannelFutureListener.CLOSE); } else if (msg instanceof PingWebSocketFrame) { ctx.writeAndFlush(new PongWebSocketFrame(msg.content())); } else if (msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame){ Packet packet = PacketDecoder.decodePacket(msg.content()); packet.setTransportType(getTransportType()); String sessionId = sessionIdByChannel.get(ctx.channel()); packet.setSessionId(sessionId); msg.release(); ctx.fireChannelRead(packet); } else { msg.release(); log.warn("{} frame type is not supported", msg.getClass().getName()); } }
@Override protected void 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().getBytes(StandardCharsets.UTF_8)); } } else if (frame instanceof BinaryWebSocketFrame) { ByteBuf buf = frame.content(); byte[] b = new byte[buf.readableBytes()]; buf.readBytes(b); synchronized (responses) { responses.add(b); } } 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()); } }
@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()); } }
/** * 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))); }
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; } }
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // 判断是否是关闭链路的指令 if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } // 判断是否是Ping消息 if (frame instanceof PingWebSocketFrame) { ctx.channel().write( new PongWebSocketFrame(frame.content().retain())); return; } // 本例程仅支持文本消息,不支持二进制消息 if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format( "%s frame types not supported", frame.getClass().getName())); } // 返回应答消息 String request = ((TextWebSocketFrame) frame).text(); if (logger.isLoggable(Level.FINE)) { logger.fine(String.format("%s received %s", ctx.channel(), request)); } ctx.channel().write( new TextWebSocketFrame(request + " , 欢迎使用Netty WebSocket服务,现在时刻:" + new java.util.Date().toString())); }
/** * 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))); }
private void notifyPingMessage(PingWebSocketFrame pingWebSocketFrame) throws ServerConnectorException { //Control message for WebSocket is Ping Message ByteBuf byteBuf = pingWebSocketFrame.content(); ByteBuffer byteBuffer = byteBuf.nioBuffer(); WebSocketMessageImpl webSocketControlMessage = new WebSocketControlMessageImpl(WebSocketControlSignal.PING, byteBuffer); webSocketControlMessage = setupCommonProperties(webSocketControlMessage); connectorFuture.notifyWSListener((WebSocketControlMessage) webSocketControlMessage); }
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws UnknownWebSocketFrameTypeException, URISyntaxException, ServerConnectorException { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (FullHttpResponse) msg); log.debug("WebSocket Client connected!"); handshakeFuture.setSuccess(); channelSession = WebSocketUtil.getSession(ctx, isSecure, requestedUri); 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) { notifyTextMessage((TextWebSocketFrame) frame, ctx); } else if (frame instanceof BinaryWebSocketFrame) { notifyBinaryMessage((BinaryWebSocketFrame) frame, ctx); } else if (frame instanceof PongWebSocketFrame) { notifyPongMessage((PongWebSocketFrame) frame, ctx); } else if (frame instanceof PingWebSocketFrame) { notifyPingMessage((PingWebSocketFrame) frame, ctx); } else if (frame instanceof CloseWebSocketFrame) { if (channelSession != null) { channelSession.setIsOpen(false); } notifyCloseMessage((CloseWebSocketFrame) frame, ctx); ch.close(); } else { throw new UnknownWebSocketFrameTypeException("Cannot identify the WebSocket frame type"); } }
private void notifyPingMessage(PingWebSocketFrame pingWebSocketFrame, ChannelHandlerContext ctx) throws ServerConnectorException { //Control message for WebSocket is Ping Message ByteBuf byteBuf = pingWebSocketFrame.content(); ByteBuffer byteBuffer = byteBuf.nioBuffer(); WebSocketMessageImpl webSocketControlMessage = new WebSocketControlMessageImpl(WebSocketControlSignal.PING, byteBuffer); webSocketControlMessage = setupCommonProperties(webSocketControlMessage, ctx); connectorListener.onMessage((WebSocketControlMessage) webSocketControlMessage); }
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)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } return true; }
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. TextWebSocketFrame frame2 = (TextWebSocketFrame) frame; String request = frame2.text(); Thread t = Thread.currentThread(); System.err.printf("%s received %s%n thread %d ", ctx.channel(), request, t.getId()); /////////////////// //Do your work here /////////////////// ctx.channel().write(new TextWebSocketFrame(request.toUpperCase())); }