pip install django-socketio eventlet gunicorn python manage.py startapp videochat pip install django-socketio eventlet gunicorn python manage.py startapp videochat python INSTALLED_APPS = [ ... 'django_socketio', ... ] MIDDLEWARE = [ ... 'django_socketio.middleware.SocketIOMiddleware', ... ] python from django.conf.urls import url from django_socketio import views urlpatterns = [ ... url(r'^socket\.io', views.socketio, name='socketio'), ... ] python @socketio.on('connect') def handle_connect(): emit('connected', {'data': 'Connected'}) @socketio.on('send_message') def handle_send_message(data): emit('receive_message', {'data': data['data']}, broadcast=True) script navigator.mediaDevices.getUserMedia({ video: true, audio: true }) .then(function (stream) { const video = document.querySelector('video'); video.srcObject = stream; const configuration = { 'iceServers': [{ 'urls': 'stun:stun.l.google.com:19302' }] }; const peerConnection = new RTCPeerConnection(configuration); peerConnection.addStream(stream); peerConnection.onnegotiationneeded = function () { peerConnection.createOffer() .then(function (offer) { return peerConnection.setLocalDescription(offer); }) .then(function () { socket.emit('send_message', { 'data': peerConnection.localDescription }); }); }; socket.on('receive_message', function (data) { peerConnection.setRemoteDescription(data); }); }) .catch(function (err) { console.error('Error accessing media devices.', err); }); socket.on('connect', function () { const video = document.querySelector('video'); video.style.display = 'block'; }); socket.on('connected', function (data) { console.log('Connected:', data); }); html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>WebRTC Video Chat</title> </head> <body> <h1>WebRTC Video Chat</h1> <video style="display: none;" width="400" height="300" autoplay=""></video> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.js"></script> <script src="{% static 'webrtc.js' %}"></script> </body> </html> python from django.urls import path from . import views urlpatterns = [ path('', views.video_chat, name='video_chat'), ] python from django.shortcuts import render def video_chat(request): return render(request, 'videochat.html')


上一篇:
下一篇:
切换中文