本地 EventBus 僅限進程內,跨服務器事件傳播需分佈式方案。選用 C# Socket + SuperSocket 框架,實現即時推送到所有訂閱相同事件的服務器。
ME [ServerIdentity]:客戶端註冊身份Subscribe [EventClassFullName]:訂閱事件類型Publish [EventClass] [EventXml]:發布事件,Server 轉發給所有訂閱該類型的其他客戶端public class ME : CommandBase{ public override void ExecuteCommand(...) { session.AssociatedServerIdentity = RestoreSpecialCharacters(requestInfo.Parameters[0]); Console.WriteLine($"[{session.AssociatedServerIdentity}] connected."); } } public class Subscribe : CommandBase<...> { public override void ExecuteCommand(...) { var classPath = RestoreSpecialCharacters(requestInfo.Parameters[0]); if (!session.SubscribedEventClasses.Contains(classPath)) session.SubscribedEventClasses.Add(classPath); // 日誌輸出訂閱列表 } } public class Publish : CommandBase<...> { public override void ExecuteCommand(...) { var evtClass = RestoreSpecialCharacters(requestInfo.Parameters[0]); foreach (var s in session.AppServer.GetAllSessions()) { if (s.AssociatedServerIdentity == session.AssociatedServerIdentity) continue; // 不回發給自己 if (s.SubscribedEventClasses.Contains(evtClass)) { s.Send("Publish " + requestInfo.Body); // 透傳原始消息體 Console.WriteLine($"Forward {evtClass} from {session.AssociatedServerIdentity} to {s.AssociatedServerIdentity}"); } } } }
var broker = new EventBusClientBroker("127.0.0.1", 2012, "AppServer2", "AppEvents.dll");
broker.NewEventReceived += (evtClass, evtObj) => {
if (evtObj is NewUserRegisteredEvent e) Console.WriteLine(e.UserName);
// ...
};
broker.Connect();
broker.Subscribe();
// 發布事件
broker.Publish(new NewUserRegisteredEvent { UserName = "aaron", RegisterDate = DateTime.Now });

Server 啟動後,多客戶端連接、訂閱、發布,事件即時轉發到訂閱者。