websocket的建立

1 nginx配置

#HTTPS  server
map $http_upgrade $connection_upgrade {
        default upgrade;
        ‘‘ close;
}
upstream websocket {
    #ip_hash;
    server localhost:3344; 
}

server {
        listen       443 ssl;
        server_name  www.report.xiaozhumaopao.com;

        ssl_certificate cert/3940071_www.report.xiaozhumaopao.com.pem;   
        ssl_certificate_key cert/3940071_www.report.xiaozhumaopao.com.key;   
        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers  on;

        location /websocket {
            proxy_pass http://websocket;
            proxy_read_timeout 300s;
            proxy_send_timeout 300s;
        
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;        

        proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection  $connection_upgrade;
        }
        location / {
            proxy_pass http://127.0.0.1:3000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}

后端 koa2

安装依赖:npm i ws -S

const WesSocket = require(‘ws‘);
var wss = new WesSocket.Server({port:3344})
var mysw = null;
wss.on(‘connection‘, function connection(ws) {
    ws.on(‘message‘, function incoming(message) {
        mysw = ws;
        console.log(‘server: received: %s‘, message);//接受客户端的信息
    });
   
});

调用发送到客户端的数据:

mysw.send(newData[0].userName);

客户端:

socketConnect() {
            let url = ‘‘;
            if(isLoc){
                url = ‘ws://localhost:3344‘;
            }else{
                url = ‘wss://www.report.xiaozhumaopao.com/websocket‘;
            }
            // 客户端与服务器进行连接
            let ws = new WebSocket(url); // 返回`WebSocket`对象,赋值给变量ws
            // 连接成功回调
            ws.onopen = e => {
                ws.send(‘我发送消息给服务端‘); // 客户端与服务器端通信
            }
            // 监听服务器端返回的信息
            ws.onmessage = e => {
                console.log(e.data);
                if(!this.updateName.includes(e.data)){
                    this.updateName.push(e.data)
                }
                ws.send(‘接受到服务端的数据‘); 
            }
        }

 

websocket的建立

上一篇:Installing Node.js & NPM on Ubuntu


下一篇:总结5.25 PHP设置目录页码跳转