Socket.io nginx Redis - 客户端未从服务器接收消息

Socket.io nginx Redis - Client not receiving messages from server

我很困惑。我在本地主机上用 Mamp 测试这个应用程序,一切正常,但是当移动到开发服务器时,客户端停止从服务器接收消息。我在 Vuejs 组件中使用它。

我在客户端上登录 socket.on('connect') 并且第二次检查返回 true。

这是我的代码:

服务器

var server = require ('http').Server();
var io = require ('socket.io')(server);
var Redis = require ('ioredis');
var redis = new Redis();


redis.subscribe('chat');

redis.on('message', (channel, message) => {
  message = JSON.parse(message);

  // channel:event:to_id:to_type - message.data
  io.emit(channel + ':' + message.event + ':' + message.to_id + ':' + message.to_type, message.data);
  console.log(message +' '+ channel);
});

server.listen('6001');

客户端

var io = require('socket.io-client')
var socket = io.connect('http://localhost:6001', {reconnect: true});
...
mounted() {
    console.log('check 1', socket.connected);
    socket.on('connect', function() {
      console.log('check 2', socket.connected);
    });

    socket.on('chat:newMessage:'+this.fromid+':'+this.fromtype, (data) => {
      console.log('new message');
      var message = {
        'msg': data.message,
        'type': 'received',
        'color': 'green',
        'pos': 'justify-content-start',
      }
      this.messages.push(message);
    });
}

Nginx 配置文件

upstream node1 {
    server 127.0.0.1:6001;
}
server {
    listen 80;
    server_name localhost;

    location / {
        #Configure proxy to pass data to upstream node1
        proxy_pass http://node1/socket.io/;
        #HTTP version 1.1 is needed for sockets
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

非常感谢!

好的,我找到了解决方案。

我正在使用 localhost

我已经替换了

var socket = io.connect('http://localhost:6001', {reconnect: true});

与:

var socket = io.connect('http://'+ window.location.hostname +':6001', {reconnect: true});

现在一切正常。