Home >Backend Development >Python Tutorial >WebRTC python server: STUN/TURN servers for your python app
Python is a versatile and accessible programming language that is known for its clear syntax and readability
This makes it a good choice for building webrtc applications
We can build a WebRTC server in python by using libraries such as aiortc
Pure python Implementation:
Built on asyncio :
Media and data channels:
Ease of Integration:
Extensive documentation and examples:
Python 3.x Installed:
python3 --version
Basic Knowledge of async programming:
using pip to install aiortc and other dependencies
aiortc is a pure python implementation of webrtcand ORTC. It uses python language async features to handle the real time communication
Install the libraries using pip like so
pip install aiortc aiohttp
aiorrtc provides the core WebRTC functionality
aiohttp is an asynchronous HTTP client/server framework, we are going to use this framework for signalling
Setting up signalling with WebSockets
WebRTC needs a signalling mechanism in order to establish a connection.
WebRTC does this by exchanging SDP or session descriptions and ICE candidates between peers
For this, you can use anything. In this article we are going to use WebSockets for real time bi directional communication between client and server
Signalling setup ( Server code)
python3 --version
Here we are going to create RTCPeerConnection object to manage the connection and the media streams
Server code example (Peer Connection)
pip install aiortc aiohttp
To handle the NAT traversal and ensure connectivity we need TURN servers.
In this article we are going with Metered TURN servers. Metered is a Global provider of TURN server
You can sign up for a free plan on Metered TURN servers that offers 50 GB monthly TURN server quota and there are paid plans also available
Steps:
Sign Up on Metered.ca/stun-turn and get your TURN credentials
On the Dashboard click on the Click here to generate your first credential button to create a new TURN server credential
Then click on the Instructions button to get your ICE server array.
You can also use the api key to enable TURN servers
import asyncio from aiohttp import web import json async def index(request): with open('index.html', 'r') as f: content = f.read() return web.Response(text=content, content_type='text/html') async def websocket_handler(request): ws = web.WebSocketResponse() await ws.prepare(request) # Handle incoming WebSocket messages here return ws app = web.Application() app.router.add_get('/', index) app.router.add_get('/ws', websocket_handler) web.run_app(app)
Here is how we can integrate everything here
from aiortc import RTCPeerConnection, RTCSessionDescription pcs = set() # Keep track of peer connections async def websocket_handler(request): ws = web.WebSocketResponse() await ws.prepare(request) pc = RTCPeerConnection() pcs.add(pc) @pc.on("datachannel") def on_datachannel(channel): @channel.on("message") async def on_message(message): # Handle incoming messages pass async for msg in ws: if msg.type == web.WSMsgType.TEXT: data = json.loads(msg.data) if data["type"] == "offer": await pc.setRemoteDescription(RTCSessionDescription( sdp=data["sdp"], type=data["type"])) answer = await pc.createAnswer() await pc.setLocalDescription(answer) await ws.send_json({ "type": pc.localDescription.type, "sdp": pc.localDescription.sdp }) elif data["type"] == "candidate": candidate = data["candidate"] await pc.addIceCandidate(candidate) elif msg.type == web.WSMsgType.ERROR: print(f'WebSocket connection closed with exception {ws.exception()}') pcs.discard(pc) return ws
STUN Servers: These help the client devices that are behind a NAT know their own IP address and port number. To learn more about STUN servers go to Stun Server: What is Session Traversal Utilities for NAT?
TURN Servers: TURN servers relay traffic from peer to per when direct communication is not possible due to NAT or firewall rules. To learn more about TURN servers go to: What is a TURN server?
Using asyncio for concurrency management
Media streams management best practices
API: TURN server management with powerful API. You can do things like Add/ Remove credentials via the API, Retrieve Per User / Credentials and User metrics via the API, Enable/ Disable credentials via the API, Retrive Usage data by date via the API.
Global Geo-Location targeting: Automatically directs traffic to the nearest servers, for lowest possible latency and highest quality performance. less than 50 ms latency anywhere around the world
Servers in all the Regions of the world: Toronto, Miami, San Francisco, Amsterdam, London, Frankfurt, Bangalore, Singapore,Sydney, Seoul, Dallas, New York
Low Latency: less than 50 ms latency, anywhere across the world.
Cost-Effective: pay-as-you-go pricing with bandwidth and volume discounts available.
Easy Administration: Get usage logs, emails when accounts reach threshold limits, billing records and email and phone support.
Standards Compliant: Conforms to RFCs 5389, 5769, 5780, 5766, 6062, 6156, 5245, 5768, 6336, 6544, 5928 over UDP, TCP, TLS, and DTLS.
Multi‑Tenancy: Create multiple credentials and separate the usage by customer, or different apps. Get Usage logs, billing records and threshold alerts.
Enterprise Reliability: 99.999% Uptime with SLA.
Enterprise Scale: With no limit on concurrent traffic or total traffic. Metered TURN Servers provide Enterprise Scalability
5 GB/mo Free: Get 5 GB every month free TURN server usage with the Free Plan
Runs on port 80 and 443
Support TURNS SSL to allow connections through deep packet inspection firewalls.
Supports both TCP and UDP
Free Unlimited STUN
The above is the detailed content of WebRTC python server: STUN/TURN servers for your python app. For more information, please follow other related articles on the PHP Chinese website!