我很困惑。我正在使用Mamp在localhost上测试这个应用程序,一切正常,但是当移动到开发服务器时,客户端停止从服务器接收消息。我在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 conf
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";
}
}
非常感谢!
答案 0 :(得分:0)
好的,我找到了解决方案。
我正在使用localhost
我已经取代了
var socket = io.connect('http://localhost:6001', {reconnect: true});
使用:
var socket = io.connect('http://'+ window.location.hostname +':6001', {reconnect: true});
现在一切正常。