【问题标题】:How to use netty as WebSocket server and HTTP client both in the same server如何在同一服务器中使用 netty 作为 WebSocket 服务器和 HTTP 客户端
【发布时间】:2017-08-27 16:00:02
【问题描述】:

我使用 Netty 作为简单的 websocket 服务器,我希望能够使用 netty 进行通信 第二个使用 HTTP 作为客户端的 netty 服务器。 怎么办?
现在我的初始化程序看起来像这样:

public class PDServerInitializer extends ChannelInitializer<Channel> {
     private final ChannelGroup group;

        public PDServerInitializer(ChannelGroup group) {
            this.group = group;
        }

        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new HttpServerCodec());
            pipeline.addLast(new HttpObjectAggregator(64 * 1024));
            pipeline.addLast(new ChunkedWriteHandler());
            pipeline.addLast(new HttpRequestHandler("/ws"));
            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
            pipeline.addLast(new TextWebSocketFrameHandler(group));
        }
}



public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private final ChannelGroup group;

    public TextWebSocketFrameHandler(ChannelGroup group) {
        this.group = group;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {

            ctx.pipeline().remove(HttpRequestHandler.class);



            group.add(ctx.channel());
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        msg.retain();
        TextWebSocketFrame frame = (TextWebSocketFrame) msg;
        String jsonRequest = frame.text(); 

       //I WAHT TO SENT THE STRING jsonRequest to NETTY Server 2 as client from here 

    }
}

服务器端工作得很好,我想将字符串“jsonRequest”作为 http 请求发送到第二个 netty,并从这个特定的服务器接收答案

【问题讨论】:

  • 你到底是什么意思?是否要向其他服务器发出传出 http 请求?
  • 是的,我发送 http 请求

标签: netty


【解决方案1】:

Http 和 WebSocket 是不同的协议。 WebSocket 所做的是使用 HTTP 请求将其连接从 HTTP 升级到 WebSocket。握手之后,netty 不会理解 HTTP 调用而是 WebSocket 帧。

但是恕我直言,如果您使用 WebSocket,则不必使用任何其他协议来实现两个对等方之间的来回通信。因为 WebSocket 通道是一个全双工通道,这意味着您可以在客户端和服务器之间使用相同的连接来发送或接收来自另一端的消息。

您必须了解的是,WebSocket 服务器和客户端之间只有细微的差别。客户端是始终启动连接的人。但就是这样。之后双方可以监听通道并将 WebSocket 帧写入通道。所以我想把连接发起者作为客户端会解决你的问题。
为您的客户尝试Netty WebSocket client example,我想这应该适用于您的场景。

【讨论】:

    猜你喜欢
    • 2018-05-21
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多