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

React Socket.io客户端无法连接Go Socket.io服务器及视频传输问题排查

问题排查与解决方案

1. 确保Socket.io版本完全匹配

Go的github.com/googollee/go-socket.io与React的socket.io-client版本必须严格对应,这是连接失败的高频原因:

  • 若Go使用v2.x分支(如go-socket.io/v2),React需安装socket.io-client@2.x
  • 若Go使用v3.x/v4.x,React要对应安装socket.io-client@3.x或4.x

查看Go项目go.mod中的依赖版本,比如:

require github.com/googollee/go-socket.io v2.0.0+incompatible

则React终端执行:

npm install socket.io-client@2.4.0

2. 配置Go服务器的CORS规则

浏览器会拦截跨域请求,必须在Go服务器中明确允许React所在域名的访问:

package main

import (
	"log"
	"net/http"

	socketio "github.com/googollee/go-socket.io"
	"github.com/googollee/go-socket.io/engineio"
	"github.com/googollee/go-socket.io/engineio/transport"
	"github.com/googollee/go-socket.io/engineio/transport/polling"
	"github.com/googollee/go-socket.io/engineio/transport/websocket"
)

func main() {
	// 允许React开发服务器域名(示例为http://localhost:3000)
	allowOrigin := func(r *http.Request) bool {
		return r.Header.Get("Origin") == "http://localhost:3000"
	}

	server, err := socketio.NewServer(&engineio.Options{
		Transports: []transport.Transport{
			&polling.Transport{CheckOrigin: allowOrigin},
			&websocket.Transport{CheckOrigin: allowOrigin},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	// 绑定socket事件逻辑...

	http.Handle("/socket.io/", server)
	log.Println("Server running on :8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

3. 修正React的Socket.io连接代码

确保在useEffect中正确初始化连接,并处理组件卸载时的资源清理:

import { useEffect, useRef } from 'react';
import io from 'socket.io-client';

function App() {
  const socketRef = useRef(null);

  useEffect(() => {
    // 指定正确的服务器地址,显式声明传输方式避免兼容性问题
    socketRef.current = io('http://localhost:8080', {
      transports: ['websocket', 'polling'],
      reconnection: true,
    });

    // 监听连接状态
    socketRef.current.on('connect', () => console.log('Connected to server'));
    socketRef.current.on('connect_error', err => console.error('Connection failed:', err));
    socketRef.current.on('disconnect', () => console.log('Disconnected'));

    // 组件卸载时断开连接
    return () => socketRef.current.disconnect();
  }, []);

  // 摄像头录制与FFmpeg转码逻辑...

  return <div>Video Stream App</div>;
}

export default App;

4. 基础网络排查

  • 确认Go服务器正常运行,监听端口(如8080)未被其他程序占用
  • 检查React开发服务器(默认3000)可正常访问
  • 打开浏览器开发者工具的Network标签,查看socket.io请求的状态码,定位是否有4xx/5xx错误

5. FFmpeg数据流发送注意事项

连接成功后若视频流传输异常,需确保:

  • FFmpeg转码输出为socket可传输的格式(如H.264编码的分片数据)
  • 分块发送大数据流时,用socket的emit方法逐块推送:
// 假设ffmpeg处理后的可读流为readableStream
readableStream.on('data', chunk => {
  socketRef.current.emit('video-stream', chunk);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:32:57