PeerJS Peer.on('call'),Socket.io 未触发

PeerJS Peer.on('call') with Socket.io not Triggering

提问人:Scott-MEARN-Developer 提问时间:12/16/2022 最后编辑:Scott-MEARN-Developer 更新时间:12/22/2022 访问量:156

问:

我正在尝试使用 Socket.io、PeerJS、Node、Express 和 Angular 创建一个视频通话应用程序。

问题是,虽然我可以很好地连接自己的视频,但我看不到其他用户的视频。事实上,Peer.on('call') 代码似乎根本没有触发。

我认为我的索引 .js 代码也可能存在问题,因为我添加到该文件的控制台 .log( 也从未出现过,并且收到以下错误消息:

无法加载资源:服务器响应状态为 404 (未找到)

我的代码如下所示:

// --- index.js:

const express = require("express");
const app = express();
const PORT = 3000;
const path = require('path');
app.set('src', path.join(__dirname, '../src'));
 

const server = require('http').Server(app)
const io = require('socket.io')(server)

io.on('connection',(socket)=>{
    console.log('backend video test 1') // THIS NEVER TRIGGERS
    socket.on('join-room',(roomId,userId)=>{
        //join the room
        console.log('backend video test 2') // THIS NEVER TRIGGERS
        socket.join(roomId)
        socket.to(roomId).broadcast.emit('user-connected',userId)

        //leave room
        socket.on('disconnect',()=>{
            console.log('backend video test 3') // THIS NEVER TRIGGERS
            socket.to(roomId).broadcast.emit('user-diconncected',userId)
        })
    })
})

app.listen(PORT, console.log(`Your app is running on port ${PORT}`))
// --- component ts file:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Socket } from 'ngx-socket-io';
import { Peer } from "peerjs";

interface VideoElement{
  muted:boolean;
  srcObject:MediaStream;
  userId:string;
}

@Component({
  selector: 'app-video-call-v2',
  templateUrl: './video-call-v2.component.html',
  styleUrls: ['./video-call-v2.component.css']
})
export class VideoCallV2Component implements OnInit {

  currentUserId:string='testUser'+Math.floor(Math.random()*1000);
  videos:VideoElement[]=[];

  constructor(
    private route: ActivatedRoute,
    private socket: Socket,
  ) {}

  ngOnInit() {
    console.log(`Init Peer with id ${this.currentUserId}`) // this works fine.
    
    //------------------------------------
    // --- Access user video and audio ---
    //------------------------------------

    navigator.mediaDevices.getUserMedia({
      audio:true,
      video:true
    }).catch((err)=>{
      console.log('user media error: ',err);
      return null
    }).then((stream:any)=>{ 

      const myPeer = new Peer(this.currentUserId,{
        host:'/',
        port:3001,
      });      
      console.log('myPeer ='); 
      console.log(myPeer) // this works fine.

      myPeer.on('open',(userId: any)=>{
        console.log('test2') // this works fine.
         console.log(userId) // this works fine.
        this.socket.emit('join-room','lessonvideo2',userId)
      });

      if (stream){        
        this.addMyVideo(stream);
        console.log(stream) // this works fine.
      } else{
        console.log('no stream found')
      }

      //-------------------------------
      // --- Receieve incoming call ---
      //-------------------------------

      myPeer.on('call',call=>{ 
        console.log(`receiving call from... ${call}`); // THIS NEVER TRIGGERS!
        call.answer(stream)

        call.on('stream',(otherUserVideoStream: MediaStream)=>{
          console.log('receiving other user stream ' + otherUserVideoStream); // THIS NEVER RUNS
          this.addOtherUserVideo(call.metadata.userId,otherUserVideoStream);
        });

        call.on('error',(err:any)=>{
          console.log(err)
        })
      }); 

      //------------------------------
      // --- Connecting other user ---
      //------------------------------

      this.socket.on('user-connected',(userId:string)=>{
        console.log('receiving user-connected event', 'Calling ' + userId);  // THIS NEVER RUNS     

        setTimeout(()=>{ // Allow some time for new peers to connect
          console.log("test3") // THIS NEVER RUNS
          const call = myPeer.call(userId,stream,{
            metadata:{userId:this.currentUserId},
          });
          call.on('stream',(otherUserVideoStream: MediaStream) =>{
            console.log('receiving other stream after...') // THIS NEVER RUNS
            this.addOtherUserVideo(userId,otherUserVideoStream)
          });

          call.on('close',()=>{
            this.videos=this.videos.filter((video)=>video.userId!==userId);
          });            
        },10000);          
      });        
    });

    //------------------------------
    // --- Disconnect other user ---
    //------------------------------

    this.socket.on('user-disconnected',(userId:string)=>{
      console.log('receiving user-doscconected event from '+ userId) // THIS NEVER RUNS
      this.videos = this.videos.filter((video)=>video.userId!==userId);
    })
  }

  addMyVideo(stream:MediaStream){
    console.log('added') // This works fine
    this.videos.push({
      muted:true,
      srcObject:stream,
      userId:this.currentUserId,
    });
  }

  addOtherUserVideo(userId:string, stream:MediaStream){
    console.log('second video added')
    const alreadyExisting = this.videos.some(video => video.userId === userId)
    if (alreadyExisting){
      console.log(this.videos, userId);
      return;
    }
    this.videos.push({
      muted:false,
      srcObject:stream,
      userId,
    })
  }
  
  onLoadedMetadata(event:Event){
    (event.target as HTMLVideoElement).play()
  }  

}

我还将以下脚本放入索引 .html 文档的正文中:

  <script src="http://localhost:3001/socket.io/socket.io.js"></script>
  <script>
    var socket = io.connect('http://localhost:3001');
    socket.on('news', function (data) {
      console.log(data);
      socket.emit('my other event', { my: 'data' });
    });
  </script>

我正在将 Socket.Io 导入我的app.module.ts文件,如下所示:

    import{SocketIoModule} from 'ngx-socket-io';
    
    //...
    //...
    
    imports: [
     SocketIoModule.forRoot({
        url:'http://localhost:3001',options: {}
      })
     ]

我正在使用以下命令运行我的 peerjs 端口:

peerjs --端口 3001

我的后端在端口 3000 上运行,我的前端在 4200 上运行,它们工作正常。

注意:我看过许多其他关于这个主题的 Stack Overflow 帖子,比如这些,但我已经尝试了提到的所有内容,但没有一个对我有用:

peer.on('calll') 永远不会被调用

Peerjs call.on “stream” 事件未触发,但 peer.on “call” 事件会触发

节点 .js Angular Express PeerJS socket.io-1.0

评论


答: 暂无答案