I m creating a video chat app with Angular, peerjs and socket.io. My problem is the user-connected event is not firing when i called it in ngOnInit of the room component.
I tried inserting all the code in the connect event, I asked chatgpt but nothing happened. There are no errors in the console, and the event is working in my backend.
This is my backend :
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);
this is my room component :
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);
}
}