using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace ET { [ObjectSystem] public class NetWSComponentAwakeSystem : AwakeSystem { public override void Awake(NetWSComponent self, int sessionStreamDispatcherType) { self.SessionStreamDispatcherType = sessionStreamDispatcherType; self.AService = new WService(); self.AService.ReadCallback = self.OnRead; self.AService.ErrorCallback = self.OnError; } } [ObjectSystem] public class NetWSComponentAwake1System : AwakeSystem> { public override void Awake(NetWSComponent self, IEnumerable prefixs) { self.AService = new WService(prefixs); self.AService.ErrorCallback += (channelId, error) => self.OnError(channelId, error); self.AService.ReadCallback += (channelId, Memory) => self.OnRead(channelId, Memory); self.AService.AcceptCallback += (channelId, IPAddress) => self.OnAccept(channelId, IPAddress); NetThreadComponent.Instance.Add(self.AService); } } [ObjectSystem] public class NetWSComponentDestroySystem : DestroySystem { public override void Destroy(NetWSComponent self) { self.AService.Dispose(); } } public static class NetWSComponentSystem { public static void OnRead(this NetWSComponent self, long channelId, MemoryStream memoryStream) { Session session = self.GetChild(channelId); if (session == null) { return; } session.LastRecvTime = TimeHelper.ClientNow(); SessionStreamDispatcher.Instance.Dispatch(self.SessionStreamDispatcherType, session, memoryStream); } public static void OnError(this NetWSComponent self, long channelId, int error) { Session session = self.GetChild(channelId); if (session == null) { return; } session.Error = error; session.Dispose(); } // 这个channelId是由CreateAcceptChannelId生成的 public static void OnAccept(this NetWSComponent self, long channelId, IPEndPoint ipEndPoint) { Session session = self.AddChildWithId(channelId, self.AService); session.RemoteAddress = ipEndPoint; // 挂上这个组件,5秒就会删除session,所以客户端验证完成要删除这个组件。该组件的作用就是防止外挂一直连接不发消息也不进行权限验证 session.AddComponent(); // 客户端连接,2秒检查一次recv消息,10秒没有消息则断开 session.AddComponent(NetThreadComponent.checkInteral); } public static Session Get(this NetWSComponent self, long id) { Session session = self.GetChild(id); return session; } public static Session Create(this NetWSComponent self, IPEndPoint realIPEndPoint, string address) { long channelId = RandomHelper.RandInt64(); Session session = self.AddChildWithId(channelId, self.AService); session.RemoteAddress = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0); session.AddComponent(NetThreadComponent.checkInteral); self.AService.Create(session.Id, realIPEndPoint, address); return session; } } }