nginx websocket 反向代理過來
阿新 • • 發佈:2020-06-29
之前寫過。程式碼放在那裡,我竟然沒看。。。
說下配置
後端是 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; }
此刻完成了