Delphi TURN 客户端
在 Delphi/C++Builder 中与 TURN 服务器通信。分配中继传输地址、管理权限和通道,然后与对称 NAT 后面的对等方交换数据 — 符合 RFC 8656 标准。
在 Delphi/C++Builder 中与 TURN 服务器通信。分配中继传输地址、管理权限和通道,然后与对称 NAT 后面的对等方交换数据 — 符合 RFC 8656 标准。
TURN 客户端 — 支持 Allocate、CreatePermission、ChannelBind、Send / Indication / Data、Refresh,所有操作均使用 RFC 8656 长期凭据签名。
设置 TURN 服务器,将凭据填入 TURNOptions.Authentication,调用 Allocate,然后对每个对等方调用 CreatePermission,再通过 SendIndication 中继数据。
uses
sgcP2P, sgcP2P_STUN_Classes, sgcP2P_STUN_Types, sgcP2P_TURN_Classes,
sgcSocket_Classes;
// TFormTURN 持有 FClient: TsgcTURNClient 和 FLog: TStringList
procedure TFormTURN.StartAllocation;
begin
FClient := TsgcTURNClient.Create(nil);
FClient.Host := 'turn.example.com';
FClient.Port := 3478;
FClient.TURNOptions.Authentication.Credentials := stauLongTermCredential;
FClient.TURNOptions.Authentication.Username := 'alice';
FClient.TURNOptions.Authentication.Password := 'secret';
FClient.OnTURNAllocate := OnTURNAllocate;
FClient.Allocate;
end;
procedure TFormTURN.OnTURNAllocate(Sender: TObject;
const aSocket: TsgcSocketConnection;
const aMessage: TsgcSTUN_Message;
const aAllocation: TsgcTURN_ResponseAllocation);
begin
FLog.Add('relay: ' + aAllocation.RelayedIP + ':' +
IntToStr(aAllocation.RelayedPort));
// 中继只为已授予权限的对等方转发
FClient.CreatePermission('192.0.2.1');
FClient.SendIndication('192.0.2.1', 5000, 'hello via TURN');
end;
// includes: sgcP2P.hpp, sgcP2P_STUN_Types.hpp, sgcP2P_TURN_Classes.hpp
TsgcTURNClient *Client = new TsgcTURNClient(this);
Client->Host = "turn.example.com";
Client->Port = 3478;
Client->TURNOptions->Authentication->Credentials = stauLongTermCredential;
Client->TURNOptions->Authentication->Username = "alice";
Client->TURNOptions->Authentication->Password = "secret";
Client->OnTURNAllocate = OnTURNAllocate;
Client->Allocate();
符合 RFC 8656 标准的 TURN 客户端 — 当仅靠 STUN 无法穿透 NAT 时,为 WebRTC 提供中继层。
Allocate 发送带 REQUESTED-TRANSPORT 的 Allocate 请求并获取中继传输地址,该地址通过 OnTURNAllocate 以 aAllocation.RelayedIP 和 RelayedPort 的形式到达。Refresh(lifetime) 可延长其生命周期,Refresh(0) 则释放分配。
CreatePermission(peerIp) 注册允许中继转发数据报的对等方。权限在 5 分钟后自动过期 — 请按需刷新。
ChannelBind(peerIp, peerPort) 绕过 36 字节的 Send/Data 开销。组件会选定通道号,编码 4 字节的 ChannelData 头部,并通过 OnTURNChannelBind 报告该绑定。
TURNOptions.Authentication.Username 和 Password 使用从 401 质询中获取的 realm 和 nonce 填充 MESSAGE-INTEGRITY。Credentials 用于选择短期或长期凭据。
对于阻断 UDP 的网络,Transport := stunTCP 会将控制通道切换到 TCP,也就是 RFC 6062 所描述的路径。随后 TURNOptions.AutoRefresh 会自动维持分配、权限和通道的有效性。
TsgcICEClient 通过其 TURNClient 属性驱动一个 TURN 客户端,而 TsgcRTCPeerConnection 依据 RTCOptions.ICEServers 中的 turn: 条目进行分配。Allocate、CreatePermission 和 ChannelBind 的整个流程都会为您自动完成。