io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame #io.netty.handler.codec.http.websocketx.PongWebSocketFrame源码实例Demo

下面列出了 io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame #io.netty.handler.codec.http.websocketx.PongWebSocketFrame 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。


/**
 * 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);

}
 
源代码2 项目: micro-integrator   文件: LogUtil.java

/**
 * 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);

}
 

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());
	}
}
 
源代码4 项目: quarkus-http   文件: FrameHandler.java

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());
        }
    }
}
 
源代码5 项目: quarkus-http   文件: FrameHandler.java

private void onPongMessage(final PongWebSocketFrame frame) {
    if (session.isSessionClosed()) {
        //to bad, the channel has already been closed
        //we just ignore messages that are received after we have closed, as the endpoint is no longer in a valid state to deal with them
        //this this should only happen if a message was on the wire when we called close()
        return;
    }
    final HandlerWrapper handler = getHandler(FrameType.PONG);
    if (handler != null) {
        final PongMessage message = DefaultPongMessage.create(Unpooled.copiedBuffer(frame.content()).nioBuffer());

        session.getContainer().invokeEndpointMethod(executor, new Runnable() {
            @Override
            public void run() {
                try {
                    ((MessageHandler.Whole) handler.getHandler()).onMessage(message);
                } catch (Exception e) {
                    invokeOnError(e);
                }
            }
        });
    }
}
 

@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();
}
 

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());
		}
	}
}
 

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()));
   }
}
 

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 (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()));
    }
}
 

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());
	}
}
 

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());
        }
    }
 
源代码13 项目: zbus-server   文件: HttpWsServer.java

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;
}
 

@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);
	}
}
 

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);
}
 

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) {

        // 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) {
    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()));
    }
}
 
源代码19 项目: netty-rest   文件: WebSocketService.java

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);
}
 
源代码20 项目: carbon-apimgt   文件: WebsocketHandler.java

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

    if ((msg instanceof CloseWebSocketFrame) || (msg instanceof PongWebSocketFrame)) {
        //if the inbound frame is a closed frame, throttling, analytics will not be published.
        outboundHandler().write(ctx, msg, promise);

    } else if (msg instanceof WebSocketFrame) {
        if (isAllowed(ctx, (WebSocketFrame) msg)) {
            outboundHandler().write(ctx, msg, promise);
            // publish analytics events if analytics is enabled
            if (APIUtil.isAnalyticsEnabled()) {
                String clientIp = getClientIp(ctx);
                inboundHandler().publishRequestEvent(clientIp, true);
            }
        } else {
            if (log.isDebugEnabled()){
                log.debug("Outbound Websocket frame is throttled. " + ctx.channel().toString());
            }
        }
    } else {
        outboundHandler().write(ctx, msg, promise);
    }
}
 
源代码21 项目: selenium   文件: WebSocketUpgradeHandler.java

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()));
  }
}
 
源代码22 项目: socketio   文件: WebSocketHandler.java

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());
  }
}
 
源代码23 项目: wind-im   文件: WsServerHandler.java

private void doWSRequest(ChannelHandlerContext ctx, WebSocketFrame wsFrame) {
	InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
	String clientIp = socketAddress.getAddress().getHostAddress();
	ChannelSession channelSession = ctx.channel().attr(ChannelConst.CHANNELSESSION).get();

	Command command = new Command();
	command.setSiteUserId(channelSession.getUserId());
	command.setClientIp(clientIp);
	command.setStartTime(System.currentTimeMillis());

	if (wsFrame instanceof TextWebSocketFrame) {
		TextWebSocketFrame textWsFrame = (TextWebSocketFrame) wsFrame;
		String webText = textWsFrame.text();
		try {
			command.setParams(webText.getBytes(CharsetCoding.UTF_8));
		} catch (UnsupportedEncodingException e) {
			logger.error("web message text=" + webText + " Charset code error");
		}
		TextWebSocketFrame resFrame = new TextWebSocketFrame(textWsFrame.text());
		ctx.channel().writeAndFlush(resFrame);

		executor.execute("WS-ACTION", command);
	} else if (wsFrame instanceof PingWebSocketFrame) {
		// ping/pong
		ctx.channel().writeAndFlush(new PongWebSocketFrame(wsFrame.content().retain()));
		logger.info("ws client siteUserId={} ping to server", command.getSiteUserId());
	} else if (wsFrame instanceof CloseWebSocketFrame) {
		// close channel
		wsHandshaker.close(ctx.channel(), (CloseWebSocketFrame) wsFrame.retain());
		WebChannelManager.delChannelSession(command.getSiteUserId());
	}
}
 

@Override
public void sendPong(final ByteBuffer applicationData) throws IOException, IllegalArgumentException {
    if (applicationData == null) {
        throw JsrWebSocketMessages.MESSAGES.messageInNull();
    }
    if (applicationData.remaining() > 125) {
        throw JsrWebSocketMessages.MESSAGES.messageTooLarge(applicationData.remaining(), 125);
    }
    undertowSession.getChannel().writeAndFlush(new PongWebSocketFrame(Unpooled.copiedBuffer(applicationData)));
}
 

@Override
public void sendPong(final ByteBuffer applicationData) throws IOException, IllegalArgumentException {
    if (applicationData == null) {
        throw JsrWebSocketMessages.MESSAGES.messageInNull();
    }
    if (applicationData.remaining() > 125) {
        throw JsrWebSocketMessages.MESSAGES.messageTooLarge(applicationData.remaining(), 125);
    }
    undertowSession.getChannel().writeAndFlush(new PongWebSocketFrame(Unpooled.copiedBuffer(applicationData)));
}
 

@Override
public void sendPong(final ByteBuffer applicationData) throws IOException, IllegalArgumentException {
    if (applicationData == null) {
        throw JsrWebSocketMessages.MESSAGES.messageInNull();
    }
    if (applicationData.remaining() > 125) {
        throw JsrWebSocketMessages.MESSAGES.messageTooLarge(applicationData.remaining(), 125);
    }
    try {
        undertowSession.getChannel().writeAndFlush(new PongWebSocketFrame(Unpooled.copiedBuffer(applicationData))).get();
    } catch (InterruptedException | ExecutionException e) {
        throw new IOException(e);
    }
}
 

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        // Check for closing frame
        if (frame instanceof CloseWebSocketFrame) {
        	handleMessageCompleted(ctx, jsonBuffer.toString());
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            SessionRegistry.destroySession(session);
            return;
        }
        if (frame instanceof PingWebSocketFrame) {
        	if (logger.isDebugEnabled())
            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        if (frame instanceof TextWebSocketFrame) {
        	jsonBuffer = new StringBuffer();
        	jsonBuffer.append(((TextWebSocketFrame)frame).text());
        }
        else if (frame instanceof ContinuationWebSocketFrame) {
        	if (jsonBuffer != null) {
        		jsonBuffer.append(((ContinuationWebSocketFrame)frame).text());
        	}
        	else {
        		comlog.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, jsonBuffer.toString());
        	jsonBuffer = null;
        }
    }
 

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
	if (frame instanceof TextWebSocketFrame) {
		TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
		System.out.println("TextWebSocketFrame:" + textFrame.text());
	} else if (frame instanceof BinaryWebSocketFrame) {
		BinaryWebSocketFrame binFrame = (BinaryWebSocketFrame) frame;
		System.out.println("BinaryWebSocketFrame:" + binFrame.toString());
	} else if (frame instanceof PongWebSocketFrame) {
		System.out.println("WebSocket Client received pong");
	} else if (frame instanceof CloseWebSocketFrame) {
		System.out.println("receive close frame");
		ctx.channel().close();
	}
}
 

@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();
    }
}
 
源代码30 项目: openzaly   文件: WsServerHandler.java

private void doWSRequest(ChannelHandlerContext ctx, WebSocketFrame wsFrame) {
	InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
	String clientIp = socketAddress.getAddress().getHostAddress();
	ChannelSession channelSession = ctx.channel().attr(ChannelConst.CHANNELSESSION).get();

	Command command = new Command();
	command.setSiteUserId(channelSession.getUserId());
	command.setClientIp(clientIp);
	command.setStartTime(System.currentTimeMillis());

	if (wsFrame instanceof TextWebSocketFrame) {
		TextWebSocketFrame textWsFrame = (TextWebSocketFrame) wsFrame;
		String webText = textWsFrame.text();
		try {
			command.setParams(webText.getBytes(CharsetCoding.UTF_8));
		} catch (UnsupportedEncodingException e) {
			logger.error("web message text=" + webText + " Charset code error");
		}
		TextWebSocketFrame resFrame = new TextWebSocketFrame(textWsFrame.text());
		ctx.channel().writeAndFlush(resFrame);

		executor.execute("WS-ACTION", command);
	} else if (wsFrame instanceof PingWebSocketFrame) {
		// ping/pong
		ctx.channel().writeAndFlush(new PongWebSocketFrame(wsFrame.content().retain()));
		logger.info("ws client siteUserId={} ping to server", command.getSiteUserId());
	} else if (wsFrame instanceof CloseWebSocketFrame) {
		// close channel
		wsHandshaker.close(ctx.channel(), (CloseWebSocketFrame) wsFrame.retain());
		WebChannelManager.delChannelSession(command.getSiteUserId());
	}
}