【问题标题】:Socket io not working after being deployed部署后 Socket io 不工作
【发布时间】:2018-06-02 12:41:04
【问题描述】:

我没有收到错误消息,但当我在 Linode 中部署我的应用程序时,io.on('connection', function(socket){ console.log('a user connected', socket.client.id); }); 似乎不起作用。

但在开发中它运行良好。

server.js (socket io)

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var port = 8002;

io.on('connection', function (socket) {
    console.log('a user connected', socket.client.id); // triggering in the development
});

http.listen(port, function () {
    console.log('Express server listening on port ' + port);
    console.log('env = ' + app.get('env') +
        '\n__dirname = ' + __dirname +
        '\nprocess.cwd = ' + process.cwd());
});

客户端 html (注意:我将 localhost 更改为我的网络应用程序 ip)

  <script src="http://localhost:8002/socket.io/socket.io.js"></script>

我的应用程序似乎正在使用 socket.io polling-xhr.js

我对此有点陌生。

【问题讨论】:

  • 在您的生产环境中,您使用的是url中的端口吗?也许它期望 socket.io 在端口 80 上。
  • @Porlune 我的服务器正在监听 port 8002 但我的应用程序正在 port 82 上运行
  • 您可以设置它,以便您的 express 应用使用与 socket.io 相同的 http 服务器。以这种方式进行设置,然后请让我们知道它是否有效。
  • 如果不想在同一个http服务器上设置socket.io,可以使用:socket.connect('localhost:8002');在客户端手动设置套接字 io 主机。
  • @Porlune 你能发表你的想法作为答案,这样我就可以正确地关注你了。

标签: javascript angularjs node.js socket.io


【解决方案1】:

我不知道这是否会解决您的特定问题,但为了在您的应用程序使用的同一端口上设置 socket.io,您可以这样配置它:

const express = require('express');
const app = express();
const http = require('http');
const hostname = 'localhost';
const port = 80;

// the express app is registered with the server
const server = http.createServer(app);

// setup socket.io and register it with the server
const io = require('socket.io').listen(server);

// tell the application to listen on the port specified
server.listen(port, hostname, function (err) {
  if (err) {
    throw err;
  }
  console.log('server listening on: ', hostname, ':', port);
});

现在 socket.io 与您的应用程序在同一个端口上运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 2018-09-30
    • 2016-03-01
    • 2023-03-03
    • 1970-01-01
    • 2019-07-07
    • 2017-11-04
    相关资源
    最近更新 更多