1

I am using ffmpeg and socket.io and I have some issues. I'm trying to send a connection request to a server written in Go through React, but I'm unable to connect to it. I tried adding the events in useEffect and it's still not working, what should I do? i attaching my code in js and in go: main.go

package main

import (
    "log"

    "github.com/gin-gonic/gin"

    socketio "github.com/googollee/go-socket.io"
)

func main() {
    router := gin.New()

    server := socketio.NewServer(nil)

    server.OnConnect("/", func(s socketio.Conn) error {
        s.SetContext("")
        log.Println("connected:", s.ID())
        return nil
    })

    server.OnEvent("/", "notice", func(s socketio.Conn, msg string) {
        log.Println("notice:", msg)
        s.Emit("reply", "have "+msg)
    })

    server.OnEvent("/", "transcoded-video", func(s socketio.Conn, data string) {
        log.Println("transcoded-video:", data)
    })

    server.OnEvent("/", "bye", func(s socketio.Conn) string {
        last := s.Context().(string)
        s.Emit("bye", last)
        s.Close()
        return last
    })

    server.OnError("/", func(s socketio.Conn, e error) {
        log.Println("meet error:", e)
    })

    server.OnDisconnect("/", func(s socketio.Conn, reason string) {
        log.Println("closed", reason)
    })

    go func() {
        if err := server.Serve(); err != nil {
            log.Fatalf("socketio listen error: %s\n", err)
        }
    }()
    defer server.Close()

    if err := router.Run(":8000"); err != nil {
        log.Fatal("failed run app: ", err)
    }
}

App.js

import './App.css';
import { useEffect } from 'react';
import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg';
import { io } from 'socket.io-client'; 

function App() {
  const socket = io("http://localhost:8000",function() {
    // Send a message to the server when the client is connected
    socket.emit('clientConnected', 'Client has connected to the server!');
  })

  const ffmpegWorker = createFFmpeg({
    log: true
  })

  // Initialize FFmpeg when the component is mounted
  async function initFFmpeg() {
    await ffmpegWorker.load();
  }

  async function transcode(webcamData) {
    const name = 'record.webm';
    await ffmpegWorker.FS('writeFile', name, await fetchFile(webcamData));
    await ffmpegWorker.run('-i', name, '-preset', 'ultrafast', '-threads', '4', 'output.mp4');
    const data = ffmpegWorker.FS('readFile', 'output.mp4');
    
    // Set the source of the output video element to the transcoded video data
    const video = document.getElementById('output-video');
    video.src = URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' }));
    
    // Remove the output.mp4 file from the FFmpeg virtual file system
    ffmpegWorker.FS('unlink', 'output.mp4');
    
    // Emit a "transcoded-video" event to the server with the transcoded video data
    socket.emit("transcoded-video", data.buffer)
  }
  
  

  let mediaRecorder;
  let chunks = [];
  
  // Request access to the user's camera and microphone and start recording
  function requestMedia() {
    const webcam = document.getElementById('webcam');
    navigator.mediaDevices.getUserMedia({ video: true, audio: true })
    .then(async (stream) => {
      webcam.srcObject = stream;
      await webcam.play();

      // Set up a MediaRecorder instance to record the video and audio
      mediaRecorder = new MediaRecorder(stream);

      // Add the recorded data to the chunks array
      mediaRecorder.ondataavailable = async (e) => {
        chunks.push(e.data);
      }

      // Transcode the recorded video data after the MediaRecorder stops
      mediaRecorder.onstop = async () => {
        await transcode(new Uint8Array(await (new Blob(chunks)).arrayBuffer()));

        // Clear the chunks array after transcoding
        chunks = [];

        // Start the MediaRecorder again after a 0 millisecond delay
        setTimeout(() => {
          mediaRecorder.start();
          
          // Stop the MediaRecorder after 3 seconds
          setTimeout(() => {
            mediaRecorder.stop();
          }, 500);
        }, 0);
      }

      // Start the MediaRecorder
      mediaRecorder.start();

      // Stop the MediaRecorder after 3 seconds
      setTimeout(() => {
        mediaRecorder.stop();
      }, 700);
    })
  }
  
  useEffect(() => {
    // Set up event listeners for the socket connection
    socket.on('/', function(){
      // Log a message when the client is connected to the server
      console.log("Connected to server!"); 
    });

    socket.on('transcoded-video', function(data){
      // Log the received data for debugging purposes
      console.log("Received transcoded video data:", data); 
    });

    socket.on('notice', function(data){
      // Emit a "notice" event back to the server to acknowledge the received data
      socket.emit("notice", "ping server!");
    });

    socket.on('bye', function(data){
      // Log the received data and disconnect from the server
      console.log("Server sent:", data); 
      socket.disconnect();
    });

    socket.on('disconnect', function(){
      // Log a message when the client is disconnected from the server
      console.log("Disconnected from server!"); 
    });
  }, [])

  return (
    <div className="App">
      <div>
          <video id="webcam" onLoadStart={initFFmpeg} muted={true}></video>
          <video id="output-video" autoPlay></video>
      </div>
      <button onClick={requestMedia}>start streaming</button>
    </div>
  );
}

export default App;

What can i do to fix it? thank you!!

1 Answer 1

0

It seems that you copied the go code from the example of the github.com/googollee/go-socket.io package. But you have removed 2 important lines:

router.GET("/socket.io/*any", gin.WrapH(server))
router.POST("/socket.io/*any", gin.WrapH(server))

You should add them back. See https://github.com/googollee/go-socket.io/blob/40f6f5036e206106b776e720eec6fe27ca21e312/_examples/gin-gonic/main.go#L55-L56.

And I found that you specified the full URL in the client code:

const socket = io("http://localhost:8000",function() {
  // Send a message to the server when the client is connected
  socket.emit('clientConnected', 'Client has connected to the server!');
})

Maybe that indicates it accesses the WebSocket across origins. If that's the case, you should set up CORS correctly. There is an example showing how to set it up. See https://github.com/googollee/go-socket.io/blob/master/_examples/gin-cors/main.go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.