htpps下使用websocket 不指定

jed , 2018-9-22 14:42 , 服务器技术 , 评论(0) , 阅读(21030) , Via 本站原创 | |
1、服务器安装node,参照http://www.dzhope.com/post/1148/

2、安装socket和pm2


  npm install socket.io
  npm install pm2 -g
ln -s /data/node/bin/pm2 /usr/bin/pm2


3、服务器建立server.js


var io = require('socket.io').listen(8888);
console.log('监听程序运行在8888端口');
io.sockets.on('connection', function (socket) {
  //接收new
  socket.on('current_price_updated', function (data) {
     console.log(data);
    //发送new
    io.sockets.emit('current_price_changed', data);
  });
});


4、运行websocket

pm2 start server.js


5、查看端口情况,是否运行成功

netstat -ntlp


6、防火墙开放端口

/sbin/iptables -I INPUT -p tcp --dport 8888 -j ACCEPT


7、nginx反向代理转发

在https配置下增加

        location /socket.io/{
                proxy_pass http://127.0.0.1:8888;

                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;
    }


8、客户端

<script src="/file/script/socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io.connect('wss://域名/socket.io/');
socket.on('connect', function () {
  console.log('连接成功');
});
socket.on('current_price_changed', function (data) {
  if(parseInt($('#itemid').val())!=parseInt(data.carid)) return;
  console.log('current_price_changed',data);
  
  $.get('/auction/current_price.php?rand='+Math.random(),{carid:data.carid},function(result){
    if(parseInt(result.code)>0){
      $('#current_price').html(result.data);
      $('#record_lists').html(result.record_lists);
      console.log('current_price update success');
    }
  },'json');
});
</script>
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]