You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express+WebSocket搭建NodeJS服务对接Flutter,Heroku部署端口地址配置问题

核心问题原因

Heroku 平台仅对外暴露一个系统自动分配的端口,即代码中通过process.env.PORT获取的端口,不支持自定义额外端口对外提供服务。你当前代码中WebSocket服务单独监听6060端口,该端口无法被外网访问,因此部署后连接失败。

服务端(index.js)修改方案

将WebSocket服务挂载到已有的Express HTTP服务上,共用同一个端口,无需额外监听新端口:

  1. 先将Express服务的启动返回值赋值给server变量
  2. WebSocket服务初始化时直接传入server参数,无需指定port
    修改后的完整代码如下:
const WebSocket = require('ws');
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/lib/index.html');
});

// 存储server实例
const server = app.listen(PORT, () => {
    console.log(`listening at: ${PORT}`)
});

var webSockets = {}

// 挂载到现有server,无需单独指定端口
const wss = new WebSocket.Server({ server })

wss.on('connection', function (ws, req)  {
    var userID = req.url.substr(1)
    console.log('User connected:', userID)
    webSockets[userID] = ws
    ws.on('message', message => {
        console.log(message)
        ws.send("success");
    })
})
Flutter端修改方案

连接地址做两处调整即可:

  • 协议从ws替换为wss,匹配Heroku默认的SSL配置
  • 去掉端口号,Heroku会自动将WSS请求转发到你的服务端口
    修改后的连接代码:
import 'package:web_socket_channel/io.dart';

channel = IOWebSocketChannel.connect('wss://example.herokuapp.com/user1');
String message = "{'cmd':'This message should be sended to Heroku'}";

channel.sink.add(message);

channel.stream.listen((message) async {
   print(message);
});
补充注意事项
  • Heroku默认会断开空闲超过55秒的WebSocket连接,建议增加心跳机制,定时发送ping包维持连接
  • 若使用免费版Heroku dyno,30分钟无请求会自动休眠,首次连接可能需要等待几秒唤醒服务

内容的提问来源于stack exchange,提问作者The_dev69

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 09:06:02