Using Twilio TURN servers for your WebRTC app
This post shows you how to create a simple Sinatra (Sinatra is a Ruby DSL for quickly creating web applications in Ruby with minimal effort) app to send you Twilio TURN servers, which can be used from your WebRTC app.
config.ru
for Sinatra app
require './app.rb'
run Sinatra::Application
Here is Sinatra app app.rb
file would look like
require 'sinatra'
require "sinatra/cors"
require 'twilio-ruby'
set :allow_origin, "http://your_web_app.com https://your_web_app.com https://local.your_web_app.me https://your_web_app.me http://dev.your_web_app.me https://dev.your_web_app.me http://your_web_app.dev https://your_web_app.dev"
set :allow_methods, "GET,HEAD,POST"
set :allow_headers, "content-type,if-modified-since"
set :expose_headers, "location,link"
get "/" do
content_type :json
# Get your Account Sid and Auth Token from twilio.com/user/account
account_sid = ENV['ACCOUNT_SID']
auth_token = ENV['AUTH_TOKEN']
# set up a client to talk to the Twilio REST API
@client = Twilio::REST::Client.new(account_sid, auth_token)
token = @client.tokens.create
token.ice_servers.to_json
end
You need to deploy Sinatra app somewhere on Heroku or any other hosting provider which gives you URL to access the web app e.g. https://your_sinatra_app.herokuapp.com/
When you hit above URL, it would send response to use freely available TURN servers.
[
{
"url": "stun:global.stun.twilio.com:3478?transport=udp",
"urls": "stun:global.stun.twilio.com:3478?transport=udp"
},
{
"url": "turn:global.turn.twilio.com:3478?transport=udp",
"username": "some_username_string",
"urls": "turn:global.turn.twilio.com:3478?transport=udp",
"credential": "some_crential_string"
},
{
"url": "turn:global.turn.twilio.com:3478?transport=tcp",
"username": "some_username_string",
"urls": "turn:global.turn.twilio.com:3478?transport=tcpe ruby file, you can name `app.rb` in "credential": "some_crential_string"
},
{
"url": "turn:global.turn.twilio.com:443?transport=tcp",
"username": "some_username_string",
"urls": "turn:global.turn.twilio.com:443?transport=tcpe ruby file, you can name `app.rb` in "credential": "some_crential_string"
}
]
Then from your JavaScript where you initialize WebRTC, you can write a function like this
var startWebrtcCall = function () {
var constraints = {
video: true,
audio: true
};
$.ajax({
url: 'https://your_sinatra_app.herokuapp.com/',
error: function(err) {
console.log("Error occurred", err);
},
success: function(iceServers) {
webrtc.setPeerConnectionConfig(iceServers);
navigator.mediaDevices
.getUserMedia(constraints)
.then(getUserMediaSuccess)
.catch(errorHandler);
},
type: 'GET'
});
}