Nginx支持websocket

支持websocket

  • 官方文档 http://nginx.org/en/docs/http/websocket.html

nginx版本

  • 要求 1.3.13以后的版本

html示例

socket = new WebSocket("ws://127.0.0.1/chat");

"ws:":websoket协议;
"127.0.0.1":nginx地址;
"chat":location指示器,表示要转向websoket服务。

nginx.conf

http {
    # websocket client请求头自带http_upgrade,映射成connection_upgrade
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    server {
        
        # chat 表示websocket请求
        location /chat {
            # 12345本机websocket 服务
            proxy_pass http://127.0.0.1:12345;
            proxy_http_version 1.1;
            # 超时设置1小时
            proxy_read_timeout   3600s; 
            # 启用支持websocket连接,nginx的功能
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
        }
    }

java代码websocket初始化

protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println("收到新连接");
                            //websocket协议本身是基于http协议的,所以这边也要使用http解编码器
                            ch.pipeline().addLast(new HttpServerCodec());
                            //以块的方式来写的处理器
                            ch.pipeline().addLast(new ChunkedWriteHandler());
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/chat", null, true, 65536 * 10));
                            ch.pipeline().addLast(new MyWebSocketHandler());
                        }

WebSocketServerProtocolHandler 指定 "/chat"

因为超时机制,超时后链路会断开,可以服务端发送定时心跳。

你可能感兴趣的:(Nginx支持websocket)