前面的實作中,我們都是使用 google 提供的 STUN server,在 後疫情時代的 WebRTC 微學習系列 第 19 篇 中我們使用 coturn 來部署並測試了 TURN server,今天我們要把他加入我們的實作中,並使用 docker compose 來整合部署。
const configuration = {
iceServers: [
{
urls: 'stun:stun.l.google.com:19302',
},
],
}
peerConn = new RTCPeerConnection(configuration)
首先在 1-on-1-webrtc 資料夾中先建立一個singaling的資料夾並把所有檔案移進去
1-on-1-webrtc
└── signaling
├── Dockerfile
├── README.md
├── cert
│ ├── cert.pem
│ └── key.pem
├── package-lock.json
├── package.json
├── public
│ ├── index.html
│ └── js
│ └── main.js
└── server.js
接著建立 一個 turn 資料夾,並在資料夾內建立Dockerfile
❯ mkdir turn
❯ cd turn
❯ touch Dockerfile
❯ cd ..
❯ tree -I 'node_modules' .
1-on-1-webrtc
├── signaling
│ ├── Dockerfile
│ ├── README.md
│ ├── cert
│ │ ├── cert.pem
│ │ └── key.pem
│ ├── package-lock.json
│ ├── package.json
│ ├── public
│ │ ├── index.html
│ │ └── js
│ │ └── main.js
│ └── server.js
└── turn
└── Dockerfile
5 directories, 10 files
在 turn/Dockerfile 中,寫入 coturn 的配置
FROM ubuntu:20.04
# Setup turn server
RUN apt-get update -y
RUN apt-get install coturn -y
EXPOSE 3478/tcp
EXPOSE 3478/udp
CMD turnserver -a -o -v -n --no-dtls --no-tls -u username:password -r testRealm & sleep infinity
再來就是建立 docker-compose.yml 文件
❯ touch docker-compose.yml
❯ tree -I 'node_modules' .
1-on-1-webrtc
├── docker-compose.yml
├── signaling
│ ├── Dockerfile
│ ├── README.md
│ ├── cert
│ │ ├── cert.pem
│ │ └── key.pem
│ ├── package-lock.json
│ ├── package.json
│ ├── public
│ │ ├── index.html
│ │ └── js
│ │ └── main.js
│ └── server.js
└── turn
└── Dockerfile
5 directories, 11 files
version: '3'
services:
turn-server:
build: ./turn/
container_name: turn-server
image: turn
ports:
- "3478:3478/tcp"
- "3478:3478/udp"
networks:
- webrtc
signaling-server:
build: ./signaling/
container_name: signaling-server
image: signaling
ports:
- "8088:8088"
networks:
- webrtc
networks:
webrtc:
在 main.js 中建立三個常數,URL 可以填寫主機的ip
const TURN_SERVER_URL = '0.0.0.0:3478'
const TURN_SERVER_USERNAME = 'username'
const TURN_SERVER_CREDENTIAL = 'password'
將 google 的 STUN server 替換為
const configuration = {
iceServers: [
{
urls: 'stun:' + TURN_SERVER_URL + '?transport=tcp',
username: TURN_SERVER_USERNAME,
credential: TURN_SERVER_CREDENTIAL,
},
{
urls: 'stun:' + TURN_SERVER_URL + '?transport=udp',
username: TURN_SERVER_USERNAME,
credential: TURN_SERVER_CREDENTIAL,
},
{
urls: 'turn:' + TURN_SERVER_URL + '?transport=tcp',
username: TURN_SERVER_USERNAME,
credential: TURN_SERVER_CREDENTIAL,
},
{
urls: 'turn:' + TURN_SERVER_URL + '?transport=udp',
username: TURN_SERVER_USERNAME,
credential: TURN_SERVER_CREDENTIAL,
},
],
}
peerConn = new RTCPeerConnection(configuration)
docker-compose up -d
打開瀏覽器 https://localhost:8088/ 測試看看
完整內容可以參考 Github
❯ git clone https://github.com/tc3oliver/1-on-1-webrtc.git
❯ cd 1-on-1-webrtc
❯ git checkout docker-compose
❯ docker-compose up -d