当应用程序托管在Heroku(Node.js)上时,无法连接到Websocket

时间:2020-05-18 16:13:28

标签: javascript node.js express heroku 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'); 

1 个答案:

答案 0 :(得分:0)

您无需在客户端上指定端口。 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'));
});