2017-09-04 90 views
0

我想通过nginx与ssl设置socketio。问题是我可以让客户端连接,但是我没有看到我期望通过套接字发送的其他事件。 (注意:这不会工作在当地只是不是我的生产服务器上)通过Nginx与SSL的SocketIO

客户端代码是在这里:

import openSocket from "socket.io-client"; 
const socket = openSocket(`${SOCKET}`); 

function subscribeToTimer(callBack) { 
    socket.on("timer", timestamp => callBack(null, timestamp)); 
    socket.emit("subscribeToTimer", 1000); 
} 

export class App extends Component { 
    constructor(props) { 
    super(props); 
    this.store = this.configureStore(); 
    subscribeToTimer((err, action) => this.store.dispatch(action)); 
    } 

和服务器:

const port = 8000 
const io = require('socket.io')() 

io.on("connection", (client) => { 
    console.log("a user connected") 
    client.on("subscribeToTimer", (interval) => { 
    console.log("a user is subscribing to timer with interval: ", interval) 
    setInterval(() => { 
     timestamp = new Date() 
     client.emit('timer', { type: 'SET_TIME', payload: timestamp }); 
    }, interval); 
    }); 
}) 

io.listen(port) 
console.log('listening on port ', port) 

这是由nginx的/etc/nginx/sites-enabled/default管理:

server { 
    <snip> 
    location /socket.io { 
    proxy_pass http://localhost:8000; 
    proxy_http_version 1.1; 
    proxy_set_header Upgrade $http_upgrade; 
    proxy_set_header Connection 'upgrade'; 
    proxy_set_header Host $host; 
    proxy_cache_bypass $http_upgrade; 
    } 
} 

当我启动服务器时,我得到:

listening on port 8000 
a user connected 

所以,客户端连接到服务器,但我没有看到subscribeToTImer事件。

这里的任何见解?

+1

开发者控制台中的任何内容? –

+0

@TarunLalwani客户端控制台中没有任何东西。我其实已经想通了,所以我会更新一个答案:) – user341493

回答

1

的问题是,可能是因为两个原因。一种是使用主机头和一个使用本地主机而不是127.0.0.1

server { 
    <snip> 
    location /socket.io { 
    proxy_pass http://127.0.0.1:8000; 
    proxy_http_version 1.1; 
    proxy_set_header Upgrade $http_upgrade; 
    proxy_set_header Connection 'upgrade'; 
    proxy_cache_bypass $http_upgrade; 
    } 
} 

我不是100%肯定的根本原因,但我已经看到了去除Host和使用127.0.0.1代替localhost与插座等问题,帮助.io在过去

0

问题原来是在配置的proxy_pass行。您需要创建一个带有指定服务器组的upstream部分,然后在proxy_pass(而不是http://localhost...)中引用该部分。

工作配置/etc/nginx/sites-enabled/default

upstream socket_nodes { 
    ip_hash; 
    server 127.0.0.1:8000; 
} 

server { 

    <-- snip --> 

    location /socket.io { 
    proxy_pass http://socket_nodes; 
    proxy_http_version 1.1; 
    proxy_set_header Upgrade $http_upgrade; 
    proxy_set_header Connection 'upgrade'; 
    proxy_set_header Host $host; 
    } 
} 
+0

不知道这是否与单个上游服务器有所不同。你可以尝试'proxy_pass http://127.0.0.1:8000;'而不是?直接在'location/socket.io' –

+0

@TarunLalwani不同于'localhost',nginx会不会处理'127.0.0.1'?它与本地主机是最合作的,所以...无论如何,我应该可以在今晚进行测试。 – user341493

+0

@TarunLalwani你是对的。 127.0.0.1:8000确实有效。谢谢! – user341493