返回

配置 Coturn 服务器

前端

当然,以下是一篇关于利用 WebRTC 和 Coturn 在 CentOS 上实现 1V1 视频聊天的专业文章:

WebRTC 与 Coturn 助力 CentOS 实现 1V1 视频聊天

Web Real-Time Communication (WebRTC) 提供了一套 API,旨在为浏览器提供实时语音通话和视频对话的能力。借助 WebRTC,您可以轻松实现从浏览器到浏览器的音频和视频通信。要通过 WebRTC 开展视频聊天,浏览器之间需要能够互相连接。这可以通过直接连接实现,前提是两个浏览器都具有公共 IP 地址,或者借助称为服务器中继的中间服务器来实现。本教程将向您展示如何在 CentOS 服务器上配置 Coturn 中继服务器,以便浏览器之间建立直接连接。

  1. 安装依赖
yum install epel-release
yum install coturn
  1. 创建证书
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/coturn/server.key -out /etc/coturn/server.crt
  1. 编辑 Coturn 配置文件
nano /etc/coturn/coturn.conf

并添加以下内容:

listening-port=3478
tls-listening-port=5349
external-ip=your_public_ip_address
allocation-strategy=best-fit
simple-algorithms=aes-128-hmac-sha1
fingerprint=/etc/coturn/server.crt
no-multicast-peers=true
no-reflexive-relay=true
cert=/etc/coturn/server.crt
key=/etc/coturn/server.key
  1. 启动 Coturn 服务器
systemctl start coturn
systemctl enable coturn
  1. 创建 HTML 页面
<!DOCTYPE html>
<html>
<head>
  
</head>
<body>
  <video id="localVideo"></video>
  <video id="remoteVideo"></video>

  <script src="script.js"></script>
</body>
</html>
  1. 创建 JavaScript 文件
const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');

const peerConnection = new RTCPeerConnection({
  iceServers: [
    {
      urls: 'stun:stun.l.google.com:19302'
    },
    {
      urls: 'turn:your_public_ip_address:3478',
      username: 'username',
      credential: 'password'
    }
  ]
});

peerConnection.onicecandidate = (event) => {
  if (event.candidate) {
    otherPeer.addIceCandidate(event.candidate);
  }
};

peerConnection.ontrack = (event) => {
  remoteVideo.srcObject = event.streams[0];
};

const offerOptions = {
  offerToReceiveAudio: true,
  offerToReceiveVideo: true
};

peerConnection.createOffer(offerOptions).then((offer) => {
  peerConnection.setLocalDescription(offer);
  otherPeer.addIceCandidate(offer);
});

otherPeer.onicecandidate = (event) => {
  if (event.candidate) {
    peerConnection.addIceCandidate(event.candidate);
  }
};

otherPeer.ontrack = (event) => {
  localVideo.srcObject = event.streams[0];
};

const answerOptions = {
  offerToReceiveAudio: true,
  offerToReceiveVideo: true
};

otherPeer.createAnswer(answerOptions).then((answer) => {
  otherPeer.setLocalDescription(answer);
  peerConnection.addIceCandidate(answer);
});
  1. 在您的浏览器中打开 HTML 页面。
  2. 点击“开始视频聊天”按钮。
  3. 输入另一个人的 IP 地址。
  4. 等待连接建立。
  5. 开始聊天!