Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

Sip-Proxy

> 开发工具
Open source

纯协议层框架,屏蔽 SIP 协议细节。业务方实现 Listener 接口(推荐)或监听 Layer 1 协议事件 接收消息,通过 ClientCommandSender / ServerCommandSender 发送命令,不直接接触 JAIN-SIP。框架内置 GB28181-2016 + GB/T 28181-20

192 stars0 likes1 views
WebsiteGitHub

About

纯协议层框架,屏蔽 SIP 协议细节。业务方实现 Listener 接口(推荐)或监听 Layer 1 协议事件 接收消息,通过 ClientCommandSender / ServerCommandSender 发送命令,不直接接触 JAIN-SIP。框架内置 GB28181-2016 + GB/T 28181-20

SIP Proxy

项目文档 | 问题反馈 | CHANGELOG

基于 Java 17 + Spring Boot 3.3.1 实现的 SIP 协议代理框架,以 Maven 库的形式集成到业务进程中使用。

核心定位:纯协议层框架,屏蔽 SIP 协议细节。业务方实现 Listener 接口(推荐)或监听 Layer 1 协议事件 接收消息,通过 ClientCommandSender / ServerCommandSender 发送命令,不直接接触 JAIN-SIP。框架内置 GB28181-2016 + GB/T 28181-2022 协议实现,单 JVM 可同时启用平台服务端(gb28181-server)和设备客户端(gb28181-client),支持级联代理场景。

架构主线:

  • 1.7.0 — 出站 Dialog 维护:BYE / SUBSCRIBE 续订 / 退订改为 dialog-aware。ServerCommandSender.deviceBye(deviceId, callId) → deviceBye(callId),ClientCommandSender.sendByeCommand(FromDevice, ToDevice) → sendByeCommand(callId),SipSender.doByeRequest(FromDevice, ToDevice) 直接删除改 doByeRequest(callId)。无 dialog 时抛 DialogNotFoundException 而非吞 481。新增进程内 DialogRegistry + DialogRegistryCleaner,INVITE / SUBSCRIBE 改走 stateful 发送,自动建立 JAIN-SIP Dialog;新增 refreshSubscribe(callId, ...) / unsubscribe(callId) API 替代历史"重发 SUBSCRIBE"做法。详见 doc/plans/1.7.0/OUTBOUND-DIALOG-PLAN.md。
  • 1.5.x — Listener 化业务接口:业务接口完全 listener 化(client 5 个 listener + server 4 个 listener,全部默认方法、按需 override);server 端 32 个 Device*Event 已收敛为 4 个 Server*Event + 强类型 payload;client 端 4 个旧 *Handler 接口与 10 个细粒度 query/config event 已删除;GB/T 28181-2022 命令集(设备升级、抓拍、PTZ 精准、SD 卡、看守位、巡航轨迹、目标跟踪、报警订阅、语音对讲、视频下载等)全量落地。详见 doc/architecture/LISTENER-LAYERED-DESIGN.md 与 doc/architecture/PROTOCOL-LAYERING-MATRIX.md。

完整版本历史见 CHANGELOG.md。

模块结构

sip-proxy
├── sip-common          # 通用 SIP 协议栈(JAIN-SIP 封装、事务注册表、缓存、指标、TimeSync);零 GB28181 代码
├── gb28181-common      # GB28181 数据模型 + GB SDP 工具(JAXB XML 实体,无业务逻辑)
├── gb28181-client      # 设备客户端:ClientCommandSender、L0 入站 handler、L1 协议事件、L2 listener API
├── gb28181-server      # 平台服务端:ServerCommandSender、L0 入站 handler、L1 协议事件、L2 listener API
└── gb28181-test        # 集成测试 + sip-gateway 业务侧单机参考实现

依赖顺序:sip-common ← gb28181-common ← gb28181-client / gb28181-server ← gb28181-test

⚠️ sip-common 协议纯净性:不允许出现任何 GB28181 关键词(gb28181 / GB28181 / gbproxy / Catalog / MobilePosition / GbSession / GbSip / GbUtil)。CI 通过 scripts/check-sip-common-purity.sh 强制校验。GB28181 相关逻辑下沉至 gb28181-common(如 GbSdpUtils、GbUtil)。详见 doc/plans/1.3.0/PROTOCOL-DECOUPLING-PLAN.md。

整体分层(部署形态)

sip-proxy 不是独立服务,而是嵌入到业务方实现的 sip-gateway 网关进程中。三层架构:

…

为什么 sip-proxy 必须与 sip-gateway 同 JVM:SipTransactionRegistry 持有的 ServerTransaction 是 JAIN-SIP 实现类(SIPServerTransactionImpl),不可序列化;RequestEvent 内部持有 socket 引用(SipProvider、Dialog),跨进程后无法回包。完整方案见 doc/architecture/LAYERED-ARCHITECTURE.md。

参考实现:gb28181-test/.../gateway/ 提供了 sip-gateway 单机版完整实现(GatewayProperties / InviteContextStore / SipEventForwarder / SipCommandController / BusinessNotifier),生产部署需将 InMemoryInviteContextStore 替换为 Redis 实现、NoopBusinessNotifier 替换为实际 HTTP/MQ 推送、nodeAddressMap 替换为 K8s/Nacos 动态发现。

典型使用场景

场景 引入模块 说明
平台服务端(接收设备注册) gb28181-server 业务系统作为 GB28181 平台,管理下级设备
设备客户端(向平台注册) gb28181-client 业务系统模拟设备,向上级平台注册
级联代理(双角色共存) gb28181-client + gb28181-server 同一进程同时作为下级平台的服务端和上级平台的客户端
自定义 SIP 扩展协议 sip-common + 自定义模块 基于 SIP 协议栈实现非 GB28181 的私有协议

快速开始

环境要求

  • Java 17+
  • Maven 3.8+
  • Redis(多节点部署必需,单机演示可用 InMemoryInviteContextStore)

引入依赖

xml

    io.github.lunasaw
    gb28181-server
    1.7.0

    io.github.lunasaw
    gb28181-client
    1.7.0

启用注解

java
@SpringBootApplication
@EnableSipServer       // 平台服务端
// @EnableSipClient    // 设备客户端(级联场景两个一起加)
public class SipGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(SipGatewayApplication.class, args);
    }
}

@EnableSipServer 自动激活 SipProxyServerAutoConfig + Gb28181CommonAutoConfig + SipProxyAutoConfig;@EnableSipClient 同理。

基础配置

yaml
sip:
  server:
    enabled: true
    ip: 0.0.0.0                     # 监听地址(推荐 0.0.0.0)
    port: 5060
    external-ip: 1.2.3.4            # NAT/多节点场景填 VIP 或公网地址
    external-port: 5060             # 不填则 fallback 到 port
    server-id: 34020000002000000001
    domain: 34020000002000000001
    realm: "34020000"
    enable-udp: true
    enable-tcp: false
  common:
    user-agent: sip-proxy           # 默认 sip-proxy
    time-sync:
      enabled: true                 # SIP/NTP 校时(详见 SipCommonProperties.TimeSync)
      mode: SIP                     # SIP / NTP / BOTH

external-ip / external-port 写入出站 SIP 包的 Via / Contact 头。多节点部署时填 VIP,确保设备后续消息能回到集群。

必须实现的 Bean

业务方至少需要实现:

Bean 用途 实现要求
DeviceSessionCache 设备会话寻址(ip / port / transport) 多节点部署必须用 Redis 等共享存储,框架默认实现仅适用单机演示
ServerDeviceSupplier 服务端设备身份 + 注册鉴权 启用 @EnableSipServer 必须实现;authenticate(userId, SIPRequest) 默认调 DigestServerAuthenticationHelper.doAuthenticatePlainTextPassword 完成摘要校验
ClientDeviceSupplier 客户端设备身份 启用 @EnableSipClient 必须实现

框架提供 DefaultServerDeviceSupplier / DefaultClientDeviceSupplier(基于配置文件),仅适用于单节点 demo 或测试场景。

业务接入:三层架构

sip-proxy 把入站消息处理拆成三层(listener 三层模型自 v1.5.0 起作为主线),业务方主入口在 L2 Listener 接口,跨切层走 L1 Layer 1 协议事件:

…

每行 cmdType 在 L0 / L1 / L2 三层的具体落点,见 doc/architecture/PROTOCOL-LAYERING-MATRIX.md。新增 cmdType 时先改矩阵,再改代码。

一、Listener 接口(业务方主入口)

Client 端(设备侧)— 5 个 listener

接口 职责 调用语义 多 listener 策略
QueryListener 平台主动查询:13 个查询 hook(Catalog/DeviceInfo/DeviceStatus/RecordInfo/Alarm/ConfigDownload/Preset/MobilePosition/PTZPosition/SDCardStatus/HomePosition/CruiseTrackList/CruiseTrack) 返回非 null = Adapter 自动 sendXxxResponse 回包;返回 null = 不回包 强制单 bean(ObjectProvider#getIfUnique()),多实例 fail fast
ControlListener 平台控制:13 个 cmdType=DeviceControl 子标签(PTZ / TeleBoot / Record / Guard / AlarmReset / IFrame / DragIn / DragOut / HomePosition / DeviceUpgrade / PtzPrecise / FormatSdCard / TargetTrack)+ Keepalive fire-and-forget 全部调用(观察者)
ConfigListener 平台配置:12 个 cmdType=DeviceConfig 子标签(BasicParam / VideoParamOpt / SVAC{En,De}code / VideoParamAttribute / VideoRecordPlan / VideoAlarmRecord / PictureMask / FrameMirror / AlarmReport / Osd / SnapShot) fire-and-forget;用 Class → Consumer 显式映射避免 instanceof 顺序陷阱 全部调用
SubscribeListener 平台订阅:4 个订阅 hook(Catalog / Alarm / MobilePosition / PTZPosition) fire-and-forget;200 OK 由协议层同步返回,listener 不能拒绝订阅 全部调用
NotifyListener 平台通知:Broadcast 语音广播 + 兜底 fire-and-forget 全部调用

Server 端(平台侧)— 4 个 listener

接口 职责 调用语义
DeviceLifecycleListener 设备生命周期:注册 / 挑战 / 在线 / 离线 / 远端地址变更(NAT 漂移) fire-and-forget
DeviceSessionListener INVITE/BYE/ACK 状态机:onInviteTrying / onInviteOk / onInviteFailure / onAck / onBye / onByeError + onServerInvite(设备主动 INVITE,含 transactionContextKey 用于异步回包) fire-and-forget;UDP 重传场景需按 callId 自行幂等
DeviceNotifyListener 设备主动通知:Alarm / Keepalive / MediaStatus / MobilePosition / UpgradeResult / SnapShotFinished / VideoUploadNotify fire-and-forget
DeviceResponseListener 设备应答:Catalog / DeviceInfo / DeviceStatus / RecordInfo / PTZPosition / SDCardStatus / HomePosition / CruiseTrack{List,Single} / DeviceConfig / ConfigDownload / PresetQuery / Subscribe / NotifyUpdate(目录变更通知) fire-and-forget

一站式 Adapter

…

业务方也可按需 implements 单个或几个 listener interface,不必继承 Adapter。

二、Layer 1 协议事件(跨切层)

适合 metrics / audit / tracing / 全链路 trace 等横切关注点,与 listener 互不干扰:

Client 端 L1 事件

事件 触发时机
ClientQueryEvent rootType=Query 的统一外层事件,多态承载 13 类 query payload
ClientControlEvent rootType=Control + cmdType=DeviceControl
ClientKeepaliveEvent cmdType=Keepalive(独立事件,与控制指令拆开)
ClientConfigEvent cmdType=DeviceConfig,多态 payload
ClientSubscribeEvent method=SUBSCRIBE
ClientNotifyEvent rootType=Notify(含 Broadcast 等)
ClientInviteEvent / ClientByeEvent / ClientAckEvent / ClientCancelEvent / ClientInfoEvent 上级 INVITE / BYE / ACK / CANCEL / INFO(INFO 含结构化 MANSRTSP)
ClientRegister{Success,Failure,Challenge,Redirect}Event 客户端注册响应

Server 端 L1 事件(v1.5.2 起从 32 个 typed event 收敛为 4 个外层事件)

事件 type/payload 覆盖语义
ServerLifecycleEvent LifecycleType ∈ {REGISTER / CHALLENGE / ONLINE / OFFLINE / REMOTE_ADDRESS_CHANGED} 注册 / 上下线 / NAT 漂移
ServerSessionEvent SessionType ∈ {INVITE_TRYING / INVITE_OK / INVITE_FAILURE / ACK / BYE / BYE_ERROR / SERVER_INVITE} INVITE 三向握手 + BYE + 设备主动 INVITE(语音对讲等场景,携带 transactionContextKey)
ServerNotifyEvent typed payload:DeviceAlarmNotify / DeviceKeepLiveNotify / MediaStatusNotify / MobilePositionNotify / UpgradeResultNotify / UploadSnapShotFinishedNotify / VideoUploadNotify 设备主动通知
ServerQueryResponseEvent typed payload:DeviceResponse(Catalog) / DeviceInfo / DeviceStatus / DeviceRecord / PTZPositionResponse / SDCardStatusResponse / HomePositionResponse / CruiseTrackListResponse / CruiseTrackResponse / DeviceConfigResponse / DeviceConfigDownloadResponse / PresetQueryResponse / DeviceOtherUpdateNotify / 订阅应答元数据 设备查询应答 + 错误返回

L1 事件携带强类型 payload,业务方既可走 listener 接口,也可 @EventListener 直接监听 L1 事件做跨切。

三、命令发送

ServerCommandSender(平台 → 设备,按 deviceId 寻址,依赖 DeviceSessionCache)

48 个出站方法,覆盖 GB/T 28181-2022 全集:

…

v1.5.1 起 ServerCommandSender 31 个 @Deprecated 静态门面方法已删除,业务侧需注入 bean 调用同名实例方法。

v1.7.0 起 deviceBye(deviceId, callId) 改为 deviceBye(callId)、SipSender.doByeRequest(FromDevice, ToDevice) 直接删除。详见下文「Dialog-Aware 出站」与 doc/plans/1.7.0/OUTBOUND-DIALOG-PLAN.md。

ClientCommandSender(设备 → 平台)

设备侧主动上报与应答(注册、心跳、Catalog 通知、报警上报、抓拍完成通知、升级结果通知、视频上传通知等)。绝大部分查询应答由 ClientListenerAdapter 在 QueryListener 返回非 null 时自动调用,业务方一般无需直接接触。

四、Dialog-Aware 出站(v1.7.0+)

INVITE 与 SUBSCRIBE 走 stateful 发送(SipMessageTransmitter.transmitStateful / transmitStatefulPreRegister),通过 ClientTransaction 让 JAIN-SIP 自动建立 Dialog,同时记录到进程内 DialogRegistry(按 callId 索引,含 kind=INVITE|SUBSCRIBE 与 expiresAtMs)。

约束:

  • BYE 必须有已建立的 dialog:deviceBye(callId) / sendByeCommand(callId) / doByeRequest(callId)。无 dialog 则抛 DialogNotFoundException,不会被设备 481 静默吞掉。
  • SUBSCRIBE 续订 / 退订必须 dialog-aware:业务方调 refreshSubscribe(callId, expires) / unsubscribe(callId),禁止历史"重发新 SUBSCRIBE"做法——会在设备侧产生孤儿订阅持续浪费带宽。
  • INVITE 200 OK 的 ACK 改用 dialog.sendAck(见 InviteResponseProcessor.sendAck),与 BYE 路径对称。

Dialog 清理路径:

场景 触发方式 路径
INVITE 主���径(BYE 后) JAIN-SIP DialogTerminatedEvent AbstractSipListener.processDialogTerminated → DialogRegistry.remove
SUBSCRIBE 自然过期 兜底定时清理(RFC 6665 §4.4.1 case 3 无 DialogTerminatedEvent) DialogRegistryCleaner @Scheduled 60s 跑一次

业务侧调用模板:

java
try {
    commandSender.deviceBye(callId);
} catch (DialogNotFoundException e) {
    // dialog 已不存在(对端先发 BYE / INVITE 还未 200 OK / callId 错误)
    log.warn("BYE 失败:dialog 不存在 callId={}", callId, e);
}

为什么需要先 deprecated 桥接的形式被否决:旧 BYE API(deviceBye(deviceId, callId))会构造缺 to-tag 的 From/To,设备直接返回 481 Call leg/Transaction does not exist,长期被静默吞掉。1.7.0 选择直接删除让编译期一次性暴露所有调用点,强制业务侧迁移到 dialog-aware 路径。

⚠️ 新增任何 in-dialog 出站请求(re-INVITE、UPDATE、INFO、server-side NOTIFY 等)必须走 stateful path 并从 DialogRegistry 取出 dialog,不要自己拼 From/`T

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Java28181clientgb28181ipc

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具