0% found this document useful (0 votes)
12 views

from flask import Flask, render_tem

Uploaded by

thearyaanthaakur
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

from flask import Flask, render_tem

Uploaded by

thearyaanthaakur
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

from flask import Flask, render_template, request, jsonify

import uuid

app = Flask(__name__)

# In-memory storage for rooms


rooms = {}

@app.route('/create_room', methods=['POST'])
def create_room():
room_id = str(uuid.uuid4())
rooms[room_id] = []
return jsonify({'room_id': room_id})

@app.route('/join_room/<room_id>', methods=['POST'])
def join_room(room_id):
if room_id in rooms:
user_id = str(uuid.uuid4())
rooms[room_id].append(user_id)
return jsonify({'user_id': user_id})
return jsonify({'error': 'Room not found'}), 404

@app.route('/get_room/<room_id>', methods=['GET'])
def get_room(room_id):
if room_id in rooms:
return jsonify({'users': rooms[room_id]})
return jsonify({'error': 'Room not found'}), 404

if __name__ == '__main__':
app.run(debug=True)
npx create-react-app video-call-app
cd video-call-app
npm start
import React, { useState, useRef, useEffect } from 'react';
import io from 'socket.io-client';

const App = () => {


const [roomId, setRoomId] = useState('');
const [userId, setUserId] = useState('');
const [peerConnections, setPeerConnections] = useState({});
const videoRef = useRef();

const createRoom = async () => {


const response = await fetch('/create_room', { method: 'POST' });
const data = await response.json();
setRoomId(data.room_id);
};

const joinRoom = async (roomId) => {


const response = await fetch(`/join_room/${roomId}`, { method: 'POST' });
const data = await response.json();
if (data.error) {
alert(data.error);
} else {
setUserId(data.user_id);
}
};

useEffect(() => {
if (userId) {
const socket = io.connect('/');
socket.emit('join', { roomId, userId });

socket.on('offer', async (data) => {


const peerConnection = new RTCPeerConnection();
peerConnections[data.from] = peerConnection;
setPeerConnections({ ...peerConnections });

peerConnection.onicecandidate = (event) => {


if (event.candidate) {
socket.emit('candidate', { to: data.from, candidate:
event.candidate });
}
};

peerConnection.ontrack = (event) => {


videoRef.current.srcObject = event.streams[0];
};

await peerConnection.setRemoteDescription(new
RTCSessionDescription(data.offer));
const answer = await peerConnection.createAnswer();
await peerConnection.setLocalDescription(answer);

socket.emit('answer', { to: data.from, answer });


});

socket.on('answer', async (data) => {


const peerConnection = peerConnections[data.from];
await peerConnection.setRemoteDescription(new
RTCSessionDescription(data.answer));
});

socket.on('candidate', async (data) => {


const peerConnection = peerConnections[data.from];
await peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
});

navigator.mediaDevices.getUserMedia({ video: true, audio: true })


.then(stream => {
videoRef.current.srcObject = stream;
stream.getTracks().forEach(track => {
Object.values(peerConnections).forEach(peerConnection => {
peerConnection.addTrack(track, stream);
});
});
});
}
}, [userId]);

return (
<div>
<button onClick={createRoom}>Create Room</button>
<input type="text" placeholder="Room ID" value={roomId} onChange={(e) =>
setRoomId(e.target.value)} />
<button onClick={() => joinRoom(roomId)}>Join Room</button>
<video ref={videoRef} autoPlay></video>
</div>
);
};

export default App;from flask_socketio import SocketIO, join_room, leave_room, emit

socketio = SocketIO(app)

@socketio.on('join')
def handle_join(data):
room_id = data['roomId']
user_id = data['userId']
join_room(room_id)
emit('user_joined', {'userId': user_id}, room=room_id)

@socketio.on('offer')
def handle_offer(data):
room_id = data['roomId']
emit('offer', data, room=room_id)

@socketio.on('answer')
def handle_answer(data):
room_id = data['roomId']
emit('answer', data, room=room_id)

@socketio.on('candidate')
def handle_candidate(data):
room_id = data['roomId']
emit('candidate', data, room=room_id)

if __name__ == '__main__':
socketio.run(app, debug=True)

You might also like