使用 SSL 通过 Nginx 进行 SocketIO

use*_*493 2 ssl nginx socket.io

我正在尝试通过 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));
  }
Run Code Online (Sandbox Code Playgroud)

和服务器:

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)
Run Code Online (Sandbox Code Playgroud)

由 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

listening on port 8000
a user connected
Run Code Online (Sandbox Code Playgroud)

因此,客户端正在连接到服务器,但我没有看到该subscribeToTImer事件。

这里有什么见解吗?

Tar*_*ani 6

这个问题可能是由于两个原因造成的。一种是使用 Host 标头,一种是使用 localhost 而不是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;
  }
}
Run Code Online (Sandbox Code Playgroud)

我不是 100% 确定根本原因,但我已经看到删除Host和使用127.0.0.1而不是localhost在过去帮助解决了 socket.io 的其他问题