我试图将一个非常简单的节点服务器部署到如下所示的heroku:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
console.log("Server started")
wss.on('connection', function connection(ws) {
console.log('Client connected');
setInterval(() => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
var testObject = {
message: new Date().toTimeString()
}
client.send(JSON.stringify(testObject));
}
});
}, 5000);
ws.on('close', () => console.log('Client disconnected'));
});
Package.json
"engines": {
"node": "12.x"
},
"scripts": {
"server": "node server.js"
},
如果我在本地启动,则我的客户会打印出时间戳。 我现在将其部署到heroku。日志显示:
2020-05-07T09:30:30.429508 + 00:00 app [web.1]:> websocket-node@1.0.0 开始/ app 2020-05-07T09:30:30.429509 + 00:00 app [web.1]:>节点 server.js 2020-05-07T09:30:30.512985 + 00:00 app [web.1]:服务器已启动
然后我更改客户端配置
// const subject = webSocket('ws://localhost:8080');
const subject = webSocket('ws://whateverwhatever.herokuapp.com:8080');
但是我没有收到服务器的答复。我想念什么?
答案 0 :(得分:0)
感谢@Tin Nguyen更改了三行代码-花费了30秒。
客户代码:
const subject = webSocket('ws://fierce-dawn-73363.herokuapp.com');
服务器代码:
const PORT = process.env.PORT || 3000;
const wss = new WebSocket.Server({ port: PORT });