我有一个使用 Socket.io 部署到 heroku 的 Node JS 应用程序。我已按照 https://devcenter.heroku.com/articles/node-websockets 提供的步骤正确设置代码,但不知何故,我似乎无法正确使用 Web 套接字。
我的所有套接字轮询请求均失败,并出现以下错误。
{"code":1,"message":"会话 ID 未知"}
当我在本地运行相同的代码时,它似乎工作正常。
客户
function createSocket() {
socket = io();
socket.on('connect', function () {
socket.emit('registerUser', { userEmail: $scope.userInfo.userEmail });
});
socket.on('list_of_files', function (data) {
$timeout(function () {
$scope.fileList = data;
});
});
}
服务器
var io = require('socket.io')(server);
io.sockets.on('connection', function (socket) {
socket.on('registerUser', function (data) {
socketClients[data.userEmail] = socket;
});
});
我还启用了heroku的会话亲和力,但仍然没有运气
我知道为时已晚,但对于那些仍在寻找答案的人来说,请尝试在客户端套接字上添加此选项。
{
path: '/socket.io',
transports: ['websocket'],
secure: true,
}
仅供参考,我在使用 nginx 和代理部署到登台服务器后遇到了这个问题
iOS 平台上同样的问题,“会话 ID 未知......”
之前
[[SocketIOClient alloc] initWithSocketURL:url config:@{@"log": @NO, @"forcePolling":@YES, @"reconnectWait":@1}];
之后
[[SocketIOClient alloc] initWithSocketURL:url config:@{@"log": @NO, @"forcePolling":@YES, @"forceWebsockets":@YES}];
当在heroku 上运行并且您有多个dyno 时,您需要确保HTTP 请求与相同的dyno 相关联,以便socket.io 能够工作。这也称为粘性会话。您可以像这样启用粘性会话:
heroku features:disable http-session-affinity -a <app name>
阅读更多相关信息这里。