Java io.netty.handler.codec.http.websocketx.CloseWebSocketFrame 代码实例

・22 分钟阅读

以下是展示如何使用io.netty.handler.codec.http.websocketx.CloseWebSocketFrame的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


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

实例 2


@Override
public void close() {
    if (channel.isOpen()) {
        onClose(1000, "Normal closure; the connection successfully completed whatever purpose for which it was created.");
        listeners.clear();
        channel.writeAndFlush(new CloseWebSocketFrame()).addListener(ChannelFutureListener.CLOSE);
    }
}
 

实例 3


@org.junit.Test
public void testCloseFrame() throws Exception {
    final int code = 1000;
    final String reasonText = "TEST";
    final AtomicReference<CloseReason> reason = new AtomicReference<>();
    ByteBuffer payload = ByteBuffer.allocate(reasonText.length() + 2);
    payload.putShort((short) code);
    payload.put(reasonText.getBytes("UTF-8"));
    payload.flip();
    final AtomicBoolean connected = new AtomicBoolean(false);
    final FutureResult latch = new FutureResult();
    final CountDownLatch clientLatch = new CountDownLatch(1);
    final AtomicInteger closeCount = new AtomicInteger();
    class TestEndPoint extends Endpoint {
        @Override
        public void onOpen(final Session session, EndpointConfig config) {
            connected.set(true);
        }
        @Override
        public void onClose(Session session, CloseReason closeReason) {
            closeCount.incrementAndGet();
            reason.set(closeReason);
            clientLatch.countDown();
        }
    }
    ServerWebSocketContainer builder = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, DefaultServer.getWorker(), DefaultServer.getBufferPool(), new CompositeThreadSetupAction(Collections.EMPTY_LIST), false, false);
    builder.addEndpoint(ServerEndpointConfig.Builder.create(TestEndPoint.class, "/").configurator(new InstanceConfigurator(new TestEndPoint())).build());
    deployServlet(builder);
    WebSocketTestClient client = new WebSocketTestClient(getVersion(), new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/"));
    client.connect();
    client.send(new CloseWebSocketFrame(code, reasonText), new FrameChecker(CloseWebSocketFrame.class, payload.array(), latch));
    latch.getIoFuture().get();
    clientLatch.await();
    Assert.assertEquals(code, reason.get().getCloseCode().getCode());
    Assert.assertEquals(reasonText, reason.get().getReasonPhrase());
    Assert.assertEquals(1, closeCount.get());
    client.destroy();
}
 

实例 4


public void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    Channel ch = ctx.channel();
    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        System.out.println("dcBus " + this.session.getSessionMode() + " received close");
        ch.close();
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        System.out.println("dcBus " + this.session.getSessionMode() + " received ping");
        ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    if (frame instanceof PongWebSocketFrame) {
        System.out.println("dcBus " + this.session.getSessionMode() + " received pong");
        return;
    }
    if (frame instanceof TextWebSocketFrame) {
        String data = ((TextWebSocketFrame) frame).text();
        //System.out.println("dcBus " + this.session.getSessionMode() + " received message: " + data);
        FuncResult<CompositeStruct> res = CompositeParser.parseJson(data);
        if (res.hasErrors()) {
                // TODO logging
                System.out.println("dcBus " + this.session.getSessionMode() + " got a bad message: " + res.getMessage());
                ch.close();             // don't stay with bad messages
                return;
        }
        this.session.receiveMessage(this.session, ch, MessageUtil.fromRecord((RecordStruct)res.getResult()));      
        return;
    }
    // TODO unhandled frame type
    // TODO logging
}
 

实例 5


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 BinaryWebSocketFrame) {
            BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) frame;
            ByteBuf content = binaryWebSocketFrame.content();
            // write to the connection
            BlaubotWebsocketConnection conn = blaubotConnectionsMap.get(ctx.channel());
            conn.writeMockDataToInputStream(content);
            return;
        }
        if (!(frame instanceof TextWebSocketFrame)) {
            throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass()
                    .getName()));
        }
        // Send the uppercase string back.
        TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) frame;
        String data = textWebSocketFrame.text();
        System.err.printf("%s received %s%n", ctx.channel(), data);
        // write the data to the connection
//        BlaubotWebsocketConnection conn = blaubotConnectionsMap.get(ctx.channel());
//        byte[] dataBytes = data.getBytes(BlaubotConstants.STRING_CHARSET);
//        conn.writeMockDataToInputStream(dataBytes);
        //ctx.channel().write(new TextWebSocketFrame(data.toUpperCase()));
    }
 

实例 6


/**
 * {@inheritDoc}
 */
@Override
public void close() {
    if (isClosed.getAndSet(true)) return;
    channel.writeAndFlush(new CloseWebSocketFrame()).addListener(ChannelFutureListener.CLOSE);
    if (closeFuture != null) {
        closeFuture.cancel(true);
    }
}
 

实例 7


private void handleWebSocketFrame(final ChannelHandlerContext ctx, WebSocketFrame frame)
{
    if (frame instanceof CloseWebSocketFrame)
    {
        // Check for closing frame
        this.handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;
    }
    else if (frame instanceof PingWebSocketFrame)
    {
        // ping pong
        ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    else if (frame instanceof TextWebSocketFrame)
    {
        // only support text frames
        try
        {
            APIObject request = this.transcoder.decodeFromString(((TextWebSocketFrame) frame).text(), APIObject.class);
            // process the request
            if (request instanceof APIRequest)
            {
                // process the request
                RequestHandler handler = this.server.getHandler(request.getClass());
                if (handler != null) handler.onRequest(this.context, (APIRequest) request);
                else ctx.channel().writeAndFlush(new TextWebSocketFrame(this.transcoder.encodeAsString(new APIError("Not found"))));
            }
            else
            {
                ctx.channel().writeAndFlush(new TextWebSocketFrame(this.transcoder.encodeAsString(new APIError("Bad request"))));
                ctx.channel().close();
            }
        }
        catch (Exception e)
        {
            logger.error("Failed to decode request", e);
            // send an error response
            ctx.channel().writeAndFlush(new TextWebSocketFrame(this.transcoder.encodeAsString(new APIError("Failed to decode request"))));
            ctx.channel().close();
        }
    }
}
 

实例 8


public void disconnect() {
    enableReconnection.set(false);
    log.info("WebSocket Client sending close");
    nettyChannel.writeAndFlush(new CloseWebSocketFrame());
    // WebSocketClientHandler will close the channel when the server
    // responds to the CloseWebSocketFrame
    nettyChannel.closeFuture().awaitUninterruptibly();
}
 

实例 9


@Override
public void close() {
  if (handshaker == null) {
    super.close();
  } else {
    endReadAndFlush();
    handshaker.close(channel, new CloseWebSocketFrame(1000, null));
  }
}
 

实例 10


@Override
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) 
    throws Exception 
{
    if (readState != ReadState.Reading) return;
    if (frame instanceof TextWebSocketFrame) {
        // Only want Text when JSON subprotocol
        if (serialization != Serialization.Json)
            throw new IllegalStateException("Received unexpected TextFrame");
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        if (logger.isDebugEnabled()) {
            logger.debug("Deserialized Wamp Message: {}", textFrame.text());
        }
        //System.out.println("Deserialized Wamp message: " + textFrame.text());
        try {
            // If we receive an invalid frame on of the following functions will throw
            // This will lead Netty to closing the connection
            ArrayNode arr = objectMapper.readValue(
                new ByteBufInputStream(textFrame.content()), ArrayNode.class);
            WampMessage recvdMessage = WampMessage.fromObjectArray(arr);
            out.add(recvdMessage);
        } finally {
        }
    } else if (frame instanceof BinaryWebSocketFrame) {
        // Only want Binary when MessagePack subprotocol
        if (serialization != Serialization.MessagePack)
            throw new IllegalStateException("Received unexpected BinaryFrame");
        // TODO: Support MessagePack
    } else if (frame instanceof PongWebSocketFrame) {
        // System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        // System.out.println("WebSocket Client received closing");
        readState = ReadState.Closed;
    }
}
 

实例 11


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()));
        }
        String request = ((TextWebSocketFrame) frame).text();
        try {
            JSONObject obj = new JSONObject(request);
            handleCommand(obj, ctx);
        } catch (JSONException e) {
            throw new IllegalArgumentException(String.format("%s is not a valid JSON object", request));
        }
    }
 

实例 12


@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        System.out.println("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        return;
    }
    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", 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();
    }
}
 

实例 13


@Override
protected void decode(final ChannelHandlerContext channelHandlerContext, final CloseWebSocketFrame frame, final List<Object> objects) throws Exception {
    final ByteBuf messageBytes = frame.content();
    final byte len = messageBytes.readByte();
    if (len <= 0) {
        objects.add(RequestMessage.INVALID);
        return;
    }
    final ByteBuf contentTypeBytes = channelHandlerContext.alloc().buffer(len);
    try {
        messageBytes.readBytes(contentTypeBytes);
        final String contentType = contentTypeBytes.toString(UTF8);
        final MessageSerializer serializer = select(contentType, Serializers.DEFAULT_REQUEST_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(true);
        try {
            objects.add(serializer.deserializeRequest(messageBytes.discardReadBytes()));
        } catch (SerializationException se) {
            objects.add(RequestMessage.INVALID);
        }
    } finally {
        contentTypeBytes.release();
    }
}
 

实例 14


@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof CloseWebSocketFrame) {
        ctx.channel().close();
        ReferenceCountUtil.release(msg);
    } else if (msg instanceof BinaryWebSocketFrame
                || msg instanceof TextWebSocketFrame) {
        ByteBufHolder frame = (ByteBufHolder) msg;
        ClientHead client = clientsBox.get(ctx.channel());
        if (client == null) {
            log.debug("Client with was already disconnected. Channel closed!");
            ctx.channel().close();
            frame.release();
            return;
        }
        ctx.pipeline().fireChannelRead(new PacketsMessage(client, frame.content(), Transport.WEBSOCKET));
        frame.release();
    } else if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        String path = queryDecoder.path();
        List<String> transport = queryDecoder.parameters().get("transport");
        List<String> sid = queryDecoder.parameters().get("sid");
        if (transport != null && NAME.equals(transport.get(0))) {
            try {
                if (!configuration.getTransports().contains(Transport.WEBSOCKET)) {
                    log.debug("{} transport not supported by configuration.", Transport.WEBSOCKET);
                    ctx.channel().close();
                    return;
                }
                if (sid != null && sid.get(0) != null) {
                    final UUID sessionId = UUID.fromString(sid.get(0));
                    handshake(ctx, sessionId, path, req);
                } else {
                    ClientHead client = ctx.channel().attr(ClientHead.CLIENT).get();
                    // first connection
                    handshake(ctx, client.getSessionId(), path, req);
                }
            } finally {
                req.release();
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    } else {
        ctx.fireChannelRead(msg);
    }
}
 

实例 15


@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
   Channel ch = ctx.channel();
   if (!handshaker.isHandshakeComplete()) {
      handshaker.finishHandshake(ch, (FullHttpResponse) msg);
      System.out.println("WebSocket Client connected!");
      handshakeFuture.setSuccess();
      return;
   }
   if (msg instanceof FullHttpResponse) {
      FullHttpResponse response = (FullHttpResponse) msg;
      throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')');
   }
   WebSocketFrame frame = (WebSocketFrame) msg;
   if (frame instanceof BinaryWebSocketFrame) {
      BinaryWebSocketFrame dataFrame = (BinaryWebSocketFrame) frame;
      super.channelRead(ctx, dataFrame.content());
   }
   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();
   }
}
 
讨论
淘淘あ西西 profile image