我正在尝试在Heroku服务器上实现SocketIO和Express服务器。
这是服务器代码:
const express = require("express");
const path = require("path");
const app = express();
const HEROKU_PORT = process.env.PORT || 8080;
var http = require("http").Server(app);
var io = require("socket.io")(http);
var clients = {};
// API calls
app.get("/api/hello", (req, res) => {
res.send({ express: "Hello From Express" });
});
if (process.env.NODE_ENV === "production") {
// Serve any static files
app.use(express.static(path.join(__dirname, "client/build")));
// Handle React routing, return all requests to React app
app.get("*", function(req, res) {
res.sendFile(path.join(__dirname, "client/build", "index.html"));
});
}
/****************************** */
io.on("connection", function(socket) {
socket.on("I am", function(msg) {
clients[msg] = socket.id;
console.log(clients);
console.log(msg, "connected");
});
socket.on("command", function(msg) {
console.log(msg);
console.log(socket.id);
io.to(clients["Home server"]).emit("button", msg);
});
});
/****************************** */
http.listen(HEROKU_PORT, function() {
console.log(`SocketIO listening on port ${HEROKU_PORT}`);
});
以上代码在我的计算机上可以完美运行。但是,当我将其加载到Heroky
上时,它会部分起作用。服务器响应 GET/api/hello
,但不支持SocketIO
连接。