【问题标题】:Why my socket.io video chat won't work on heroku?为什么我的 socket.io 视频聊天无法在 heroku 上运行?
【发布时间】:2022-01-21 00:54:46
【问题描述】:

我是 WS 和 Heroku 的新手……所以我有这个代码

//我猜这会设置客户端套接字

    import {io} from 'socket.io-client';
    
    const options = {
      "force new connection": true,
      reconnectionAttempts: "Infinity", 
      timeout : 10000, 
      transports : ["websocket"]
    }
    
const socket = io('/', options)

export default socket;

对于服务器端

    const path = require('path');
    const express = require('express');
    const app = express();
    const server = require('http').createServer(app);
    const io = require('socket.io')(server);
    const {version, validate} = require('uuid');
    
    const ACTIONS = require('./src/socket/actions');
    const PORT = process.env.PORT || 3001;
///more code

当部署到 heroku 时,这会导致这个应用程序 https://lit-atoll-99067.herokuapp.com/ 和 chrome 控制台显示:

WebSocket 连接到 'wss://lit-atoll-99067.herokuapp.com/socket.io/?EIO=4&transport=websocket' 失败:在建立连接之前关闭 WebSocket。

所以我的想法用完了。但我想这一定是关于港口什么的……真的不知道。欢迎任何想法!

【问题讨论】:

    标签: javascript node.js heroku websocket socket.io


    【解决方案1】:

    我认为您需要在客户端传递完整的 URL,但您仅传递了“/”示例:-

    import {io} from 'socket.io-client';
        
    const options = {
      "force new connection": true,
       reconnectionAttempts: "Infinity", 
       timeout : 10000, 
       transports : ["websocket"]
    }
    // here need to pass the full url
    const socket = io('https://example.com/', options)
    
    export default socket;
    

    对于服务器端试试这个

    const express = require('express');
    const app = express();
    const http = require('http');
    const server = http.createServer(app);
    const { Server } = require("socket.io");
    const io = new Server(server);
    
    io.on('connection', (socket) => {
      console.log('a user connected');
    });
    
    server.listen(3000, () => {
      console.log('listening on *:3000');
    });
    

    【讨论】:

    • 嗨!这对我不起作用。我仍然收到控制台警告,并且用户之间没有建立 ws 连接。
    • 它是否在您的本地环境中工作
    • 你好。是的,当我初始化像const socket = io('http://localhost:3001', options) 这样的客户端套接字时它确实有效;
    • 而且它也可以通过初始化在heroku上运行,但只能在我的机器上运行,所以我可以打开其他浏览器并且会有ws连接,但由于它是本地主机......当我运行时它不起作用想和其他人交谈。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 2016-02-06
    • 1970-01-01
    • 2017-07-01
    • 2018-07-30
    • 2011-11-04
    相关资源
    最近更新 更多