首页 > 解决方案 > 当应用程序托管在 Heroku (Node.js) 上时,无法连接到 Websocket

问题描述

我尝试将使用 Websockets 的应用程序部署到 Heroku,但无法连接到侦听端口。

//Server
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8000 });
app.use(express.static(__dirname + '/client/dist'))
app.use(bodyParser.json());
app.listen(port, () => console.log(`Running on port ${port}`));
//Client
this.webSocket = new WebSocket('ws://jitsigame.herokuapp.com:8000'); 

标签: javascriptnode.jsexpressherokuwebsocket

解决方案


您无需在客户端指定端口。Heroku 在此处提供了详细指南:https ://devcenter.heroku.com/articles/node-websockets

//Client
this.webSocket = new WebSocket('ws://jitsigame.herokuapp.com');

您可能还想在服务器端添加连接处理程序。

wss.on('connection', (ws) => {
  console.log('Client connected');
  ws.on('close', () => console.log('Client disconnected'));
});

推荐阅读