【发布时间】:2019-09-29 22:01:01
【问题描述】:
基本上,我的 socket.io 服务器只适用于.. 一台计算机,我想。如果我使用 Chrome、Chrome incognito、Edge,它就可以工作。我尝试在手机上使用该应用程序,同时在同一个 Wifi 上,这就是我遇到问题的地方。看起来socket.io当时就行不通了。我觉得它只适用于一个客户(可能是 ip、端口问题?)
我将 socket.io 与 React js 配对使用,哦,天哪,让它们在本地和 Heroku 上工作真是太痛苦了。
这是我的服务器文件 /src/server/index.js
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const axios = require("axios");
const port = process.env.PORT || 4001; // Only this port works for some reason
const index = require("./routes/index");
const app = express();
const path = require('path');
const server = http.createServer(app);
const io = socketIo(server); // < Interesting!
io = socketIo.listen(app);
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10); // Recommended from online guys
});
app.use(express.static(path.join(__dirname, '../../index')));
app.get('/', (req, res, next) =>
res.sendFile(index))
io.on("connection", socket => {
console.log("New client connected");
})
server.listen(port, () => console.log(`Listening on port ${port}`));
我使用配置文件动态更改服务器,每次需要通过 socket.io-client 连接到我的套接字时我都会导入它
let server = 'ws://XXXXXXXXXXXXX.herokuapp.com/socket.io/?EIO=4&transport=websocket';
const env = process.env.NODE_ENV;
if (env === 'development') {
server = 'http://127.0.0.1:4001';
}
module.exports = server;
可能是什么问题?为什么只在我的根计算机上工作?可能是测功机问题或其他问题? 我是 heroku 和 socket.io 的初学者,所以任何信息都会有所帮助。
**编辑:
我不确定,但我觉得在我的 VS Code 中运行的服务器让它在我的 heroku 应用程序中运行。我已将其关闭,服务器只是不断发送 net::ERR_CONNECTION_REFUSED 错误。
【问题讨论】:
-
我也有同样的问题,Socket.IO 在 localhost 上工作,但在 Heroku 上失败。
-
@TríPhan 我搞定了。看一下这个。
Choosing the right buildpack can help, and neither heroku/heroku-buildpack-static nor mars/create-react-app-buildpack is the right choice if you've got back-end code: "If your goal is to make a single app that combines React UI with a server-side backend (Node, Ruby, Python…), then this buildpack is not the answer." But the mars one recommends mars/heroku-cra-node if you have a Node.js back-end.– 克里斯 -
@TríPhan 正如我在新线程中所说的
https://stackoverflow.com/questions/56131883/how-do-i-rewrite-all-urls-to-index-html-in-heroku -
啊,我刚刚解决了我的问题,
dotenv模块让我的应用在 Heroku 上出错,我将其删除
标签: node.js sockets heroku websocket socket.io