nginx websocket 反向代理过来

之前写过。代码放在那里,我竟然没看。。。

说下配置

后端是 nest,使用的的 @nestjs/websockets 应该是 socket.io

前端代码

<script crossorigin="anonymous" integrity="sha384-nBK38bnVsoQvGdJGVtKno9hHFpl07bff81Db7PBpo7qN1KEA8b46Mm9dJSuf78bh" src="https://lib.baomitu.com/socket.io/2.3.0/socket.io.dev.js"></script>

const test = io('ws://localhost:3021/wssocket').connect();
    test.emit('receiveMsg', 'socket2', { 'socket2': 'socket2' } );

    const socket1 = io('ws://localhost').connect(); 
    socket1.on('message', function(){
      console.log(arguments);
    });
    //断开事件
    socket1.on('disconnect', function () { // 这里监听 disconnect,就可以知道谁断开连接了
        console.log('断开连接: ' + socket1.id);
    });


    const wssocket = io('ws://localhost').connect(); 
    wssocket.on('message', function(){
      console.log(arguments);
    });

    $('#btn_send').click(()=>{
        wssocket.emit('receiveMsg', 'socket2', { 'socket2': 'socket2' } );
        socket1.emit('receiveMsg', 'socket2', { 'socket2': 'socket2' } );
    })

 

 

接着看nginx 反向代理 因为是 socket.io.dev.js 所以代理那块必须修改,上代码

#这段代码在http里面

map $http_upgrade $connection_upgrade {
  default upgrade;
  '' close;
}

#这段代码在server 里面

location /socket.io {
    #此处改为 socket.io 后端的 ip 和端口即可
    proxy_pass  http://localhost:3021;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_http_version 1.1;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
}    

此刻完成了

 

posted @ 2020-06-29 20:12  qkstart  阅读(306)  评论(0编辑  收藏  举报