我正在 Windows 计算机上运行 socket.io 服务器,并希望可以使用其公共 IP 通过互联网访问它。这是我到目前为止所做的:
端口转发:已成功打开端口 5000 并将其转发到我的 Windows 计算机。
防火墙:允许所有网络(公共、私有、域)在端口 5000 (TCP) 上进行入站流量。
本地测试:当客户端通过本地 IP (http://10.0.0.127:5000) 连接时有效。
此外,检查https://portchecker.co/端口(5000)是否已打开。
尽管进行了这些配置,但使用我的公共 IP 时仍无法访问服务器。如何正确配置我的 socket.io 远程服务器以通过公共 IP 进行访问?
//server.js
const { createServer } = require('http');
const { Server } = require('socket.io');
const httpServer = createServer();
const io = new Server(httpServer, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
});
const port = process.env.PORT || 5000;
httpServer.listen(port, () => {
console.log(`Socket.io server running on port ${port}`);
});
让这些工作起来简直就是一场噩梦。 我的代码通常看起来像 ..
const https = require("https")
const WebSocket = require('ws')
然后..
// have to fire up a https (that's "s") >>specifically for<< your wss
let for_2666 = https.createServer(main.certs).listen(2666, (err) => {
if (err) { return console.log('2828 woe', err) }
})
// and then ..
let WSServer = WebSocket.Server
let wss = new WSServer({
server: for_2666,
perMessageDeflate: false
})
console.log("mp rt server 2666 AOK")
和..
wss.on('connection', function connection(u) {
// Any and all messages arrive:
u.on('message', function incoming(m) {
.. handle incoming commands from this connection
})
u.on('close', async function incoming(codeNumber, codeReason) {
.. handle close from this connection
})
// possibly send welcome message etc
})
const interval = setInterval(function ping() {
.. send pings (a whole artform)
}, pingBasis)
wss.on('close', function close() { // SERVER close!! not a connection close!!
.. handle somewhow
})
希望有帮助