Delphi TURN 服务器
在 Delphi 中运行您自己的 TURN(RFC 8656)服务器。为无法建立点对点路径的客户端分配中继传输地址,支持长期凭据和按分配配额管理。
在 Delphi 中运行您自己的 TURN(RFC 8656)服务器。为无法建立点对点路径的客户端分配中继传输地址,支持长期凭据和按分配配额管理。
自托管 TURN 服务器 — 处理 Allocate / CreatePermission / ChannelBind / Send / Refresh / Data,管理分配及其生命周期,验证长期凭据。
设置 Port 以及 TURNOptions.Authentication.LongTermCredentials 上的 realm,通过 OnSTUNRequestAuthorization 提供每用户密码,Active := True — 您的服务器现在即可为任何 RFC 8656 客户端分配中继。
uses
sgcP2P, sgcP2P_STUN_Classes;
// TFormTURNServer 持有 FServer: TsgcTURNServer 和事件处理程序
procedure TFormTURNServer.StartServer;
begin
FServer := TsgcTURNServer.Create(nil);
FServer.Port := 3478;
FServer.TURNOptions.Authentication.Enabled := True;
FServer.TURNOptions.Authentication.LongTermCredentials.Enabled := True;
FServer.TURNOptions.Authentication.LongTermCredentials.Realm :=
'turn.example.com';
// 限制滥用:每用户分配数和最大生命周期
FServer.TURNOptions.Allocation.MaxUserAllocations := 4;
FServer.TURNOptions.Allocation.MaxLifeTime := 3600;
FServer.OnSTUNRequestAuthorization := OnSTUNRequestAuthorization;
FServer.Active := True;
end;
procedure TFormTURNServer.OnSTUNRequestAuthorization(Sender: TObject;
const aRequest: TsgcSTUN_Message;
const aUsername, aRealm: string;
var Password: string);
begin
// 返回该用户的密码,为空表示拒绝该请求
Password := LookupPassword(aUsername);
end;
// includes: sgcP2P.hpp, sgcP2P_STUN_Classes.hpp
TsgcTURNServer *Server = new TsgcTURNServer(this);
Server->Port = 3478;
Server->TURNOptions->Authentication->Enabled = true;
Server->TURNOptions->Authentication->LongTermCredentials->Enabled = true;
Server->TURNOptions->Authentication->LongTermCredentials->Realm = "turn.example.com";
Server->TURNOptions->Allocation->MaxUserAllocations = 4;
Server->OnSTUNRequestAuthorization = OnSTUNRequestAuthorization;
Server->Active = true;
自托管中继服务器 — 让您的 WebRTC 和 ICE 部署不再依赖第三方 TURN 提供商。
响应带 REQUESTED-TRANSPORT 的分配请求,选择空闲中继端口并追踪生命周期。Refresh 延长分配;服务器在过期时自动销毁。
追踪每个分配的对等方权限和通道绑定。按照 RFC 8656 §9,丢弃未经授权的对等方的 Send/Data 帧。
同时支持 36 字节的 Send/Data 包封和 4 字节的 ChannelData 帧。中继在中继传输地址和绑定对等方之间转发数据报。
TURNOptions.Authentication.LongTermCredentials 保存 realm,OnSTUNRequestAuthorization 将用户名和该 realm 交给您,由您返回密码。服务器会自行验证 MESSAGE-INTEGRITY 并轮换 nonce。
TURNOptions.Allocation.MaxUserAllocations 限制单个用户可获得的中继数量,DefaultLifeTime 和 MaxLifeTime 限制每个中继的存活时长,MinPort / MaxPort / RelayIP 则固定中继端口范围。超出限制的用户会收到 486 Allocation Quota Reached。
OnTURNBeforeAllocate 提供请求方地址以及一个 var Reject 参数,OnTURNBeforeRelayIndication 和 OnTURNBeforeRelayChannelData 对每个被中继的数据报做同样的事。OnTURNCreateAllocation 和 OnTURNDeleteAllocation 则跟踪当前存活的分配。
关于在 Delphi 和 C++ Builder 中运行自托管 TURN 中继的常见问题。
TsgcTURNServer 组件,设置 Port 和 Realm,从 OnSTUNRequestAuthorization 事件提供每用户密码,然后设置 Active := True。服务器随后会为任何 RFC 8656 客户端处理 Allocate、CreatePermission、ChannelBind、Send、Refresh 和 Data,在中继传输地址与绑定对等方之间转发数据报。TsgcTURNServer 是一个自托管中继,可嵌入您自己的 Delphi 或 C++ Builder 应用程序中,因此您的 WebRTC 和 ICE 部署可以不再依赖第三方 TURN 提供商或单独的 coturn 安装。按分配的配额(每用户最大分配数、带宽和生命周期)可限制滥用,并通过 OnQuotaExceeded 报告拒绝情况。