322-Nginx反向代理websocket 配置wss[微信小

2019-08-09  本文已影响0人  霄峰

参考地址:https://www.nginx.com/blog/websocket-nginx/

1. Nodejs写的服务端server.js

console.log("Server started");
var Msg = '';
var WebSocketServer = require('ws').Server
    , wss = new WebSocketServer({port: 4431});
    wss.on('connection', function(ws) {
        ws.on('message', function(message) {
        console.log('Received from client: %s', message);
        ws.send('Server received from client: ' + message);
    });
 });

然后运行:

$ node server.js

2. Nginx配置(以nst-wss.yunfeng365.com域名为例):

$ sudo vim /etc/nginx/site-avaliable/nst-wss.yunfeng365.com

内容如下:

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

        upstream websocket {
            server 127.0.0.1:4431; #代理到ws服务地址
        }

        server {
                # SSL configuration
                #
                listen 443;

                ssl on;
                ssl_certificate /var/cert/nst-wss.yunfeng365.com.crt;
                ssl_certificate_key /var/cert/nst-wss.yunfeng365.com.key;

                ssl_session_timeout 5m;

                ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
                ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES";
                ssl_prefer_server_ciphers on;

                underscores_in_headers on;#开启自定义头信息的下划线
                server_name nst-wss.yunfeng365.com;
                location / {
                        proxy_pass http://websocket;#代理到上面的地址去
                        proxy_http_version 1.1;
                        proxy_set_header Upgrade $http_upgrade;
                        proxy_set_header Connection $connection_upgrade;
                }
        }

创建完成后,增加nginx服务软链:

$ sudo ln -s /etc/nginx/sites-available/nst-wss.yunfeng365.com /etc/nginx/sites-enabled/
$ sudo service nginx restart

3. 完成,并使用微信开发者工具测试:
在小程序app.js中添加如下方法:

/**
 * 连接
 */
function initWebSocket() {
  // 连接
  wx.connectSocket({
    url: 'wss://nst-wss.yunfeng365.com',// webSocket 地址
    header: {'content-type': 'application/json'},
    success: function (res) {
      console.log('连接 success ', res);

      // 打开连接
      wx.onSocketOpen(function (res) {
        console.log('打开连接 ', res);
      })
    },
    fail: function (res) {
      console.log('连接 err ', res);
    }
  })
}

在小程序app.js中找到onLaunch并添加如下内容:

    onLaunch: function(options) {
        // console.info('APP Lanuch ===> ', options);
      initWebSocket();
    },

结果:

连接 success  {socketTaskId: 1, errMsg: "connectSocket:ok"}
上一篇下一篇

猜你喜欢

热点阅读