Files
nexus/wiki/concepts/RPC-Remote-Procedure-Call.md
2026-04-26 12:02:53 +08:00

60 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "RPC (Remote Procedure Call)"
type: concept
tags: []
sources: [unreal-multiplayer-architect]
last_updated: 2026-04-26
---
## Definition
远程过程调用RPC是 UE5 多人游戏中客户端与服务器之间进行通信的核心机制。客户端通过 RPC 向服务器发送请求Server RPC服务器通过 RPC 向客户端或所有客户端广播事件Client RPC / NetMulticast
## RPC Types
| 类型 | 方向 | 可靠性 | 用途 |
|------|------|--------|------|
| `Server` | 客户端 → 服务器 | Reliable/Unreliable | 客户端请求服务器执行操作 |
| `Client` | 服务器 → 特定客户端 | Reliable/Unreliable | 服务器通知特定客户端 |
| `NetMulticast` | 服务器 → 所有客户端 | Reliable/Unreliable | 服务器广播事件 |
## Critical Rule: WithValidation
**每个游戏影响型的 Server RPC 必须实现 `_Validate()` 函数。** 缺失 `_Validate()` 构成安全漏洞,恶意客户端可发送非法请求。
```cpp
// Server RPC 必须有 WithValidation
UFUNCTION(Server, Reliable, WithValidation)
void ServerRequestInteract(AActor* Target);
bool AMyActor::ServerRequestInteract_Validate(AActor* Target)
{
// 拒绝不可能的请求
if (!IsValid(Target)) return false;
float Distance = FVector::Dist(GetActorLocation(), Target->GetActorLocation());
return Distance < 200.f; // 最大交互距离
}
void AMyActor::ServerRequestInteract_Implementation(AActor* Target)
{
// 验证通过后安全执行
PerformInteraction(Target);
}
```
## Reliability Guidelines
- **Reliable**:保证按序到达,用于游戏关键事件(伤害、得分、道具拾取)
- **Unreliable**:即发即忘,不保证到达,用于视觉效果、高频位置同步
- 绝不能将高频调用与可靠 RPC 混合——必须为高频数据创建独立的不可靠更新路径
## Connection to Other Concepts
- [[Server-Authoritative Model]] — RPC 是服务器权威执行的游戏请求入口
- [[Actor Replication]] — 属性复制与 RPC 互补复制状态、RPC 触发动作
- [[Network Prediction]] — 客户端在等待服务器 RPC 响应时进行本地预测
## Relationship to Agent
[[UnrealMultiplayerArchitect]] 将 RPC 验证视为非妥协原则:"Every Server RPC needs a `_Validate`. No exceptions."
## Aliases
- Remote Procedure Call
- Server RPC
- Client RPC
- NetMulticast