用户连接的事件未在视频聊天应用(Angular、PeerJS 和 Socket.IO)中触发

User-connected event is not firing in a video chat app (Angular, PeerJS and Socket.IO)

提问人:Aymen Omri 提问时间:8/17/2023 最后编辑:pierpyAymen Omri 更新时间:8/25/2023 访问量:50

问:

我正在使用 Angular、peerjs 和 socket.io 创建一个视频聊天应用程序。我的问题是,当我从房间组件中调用用户连接事件时,它没有触发。
我尝试在连接事件中插入所有代码,我问了chatgpt,但什么也没发生。控制台中没有错误,并且该事件在我的后端工作。
ngOnInit

这是我的后端:

let express = require("express");
let bodyParser = require('body-parser');
app = express();
let server = require('http').Server(app);
let io = require('socket.io')(server, {
    cors: {
        origin: "http://localhost:4200",
        methods: ["GET", "POST"]
    }
});

app.use(express.json());

app.use(bodyParser.urlencoded({
    extended: true
}));

app.get('/test', (req, res) => {
    res.json({ message: "success" });
});


io.on('connection', (socket) => {
    socket.on('join-room', (roomId, userId) => {
        socket.join(roomId);
        socket.to(roomId).emit('user-connected', userId, () => {
            console.log('user connected:' + userId)
        });

        socket.on('disconnect', () => {
            socket.to(roomId).emit('user-disconnected', userId);
        });
    });

    // Handle the video stream from a peer
    socket.on('stream', (roomId, stream) => {
        socket.to(roomId).broadcast.emit('stream', stream);
    });
});


server.listen(3002);

这是我的房间组件:

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Peer } from 'peerjs';
import { io } from 'socket.io-client';
import { v4 as uuidv4 } from 'uuid';


@Component({
  selector: 'app-room',
  templateUrl: './room.component.html',
  styleUrls: ['./room.component.css']
})
export class RoomComponent implements OnInit {
  peer: Peer | undefined;
  roomId: string = '';
  remoteStreams: MediaStream[] = [];

  @ViewChild('localVideo') localVideo!: ElementRef;
  @ViewChild('remoteVideoContainer') remoteVideoContainer!: ElementRef;

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.roomId = this.route.snapshot.paramMap.get('room')!;

    this.peer = new Peer(uuidv4(), {
      host: 'localhost',
      port: 3001,
      path: '/',
    });

    this.peer.on('open', () => {
      console.log('My Peer ID:', this.peer?.id);
      const socket = io('http://localhost:3002');

      socket.on('connect', () => {
        console.log('Socket.IO connected');
        socket.emit('join-room', this.roomId, this.peer?.id);
      });

      socket.on('user-connected', (userId) => {
        console.log('User connected:', userId);
        this.callUser(userId);
      });

      socket.on('user-disconnected', (userId) => {
        console.log('User disconnected:', userId);
      });

      socket.on('stream', (stream) => {
        this.addRemoteStream(stream);
      });
    });
  }

  callUser(userId: string) {
    navigator.mediaDevices
      .getUserMedia({ video: true, audio: true })
      .then((stream) => {
        console.log("stream");
        this.localVideo.nativeElement.srcObject = stream;
        const call = this.peer!.call(userId, stream);

        call.on('stream', (remoteStream) => {
          this.addRemoteStream(remoteStream);
        });

        this.peer!.on('call', (incomingCall) => {
          incomingCall.answer(stream);

          incomingCall.on('stream', (remoteStream) => {
            this.addRemoteStream(remoteStream);
          });
        });
      })
      .catch((err) => {
        console.error('Failed to get local stream', err);
      });
  }
  addRemoteStream(remoteStream: MediaStream) {
    this.remoteStreams.push(remoteStream);
    const remoteVideo = document.createElement('video');
    remoteVideo.srcObject = remoteStream;
    remoteVideo.autoplay = true;
    this.remoteVideoContainer.nativeElement.appendChild(remoteVideo);
  }
}
Angular Express socket.io peerjs 视频聊天

评论


答: 暂无答案