/// <summary> /// 发送网络数据 /// </summary> /// <param name="data"></param> public void SendMsg(byte[] data) { //创建流,准备异步写入发送 NetworkStream ns = null; try { //指定写入的socket ns = new NetworkStream(skt); //判断是否可以支持写入消息 if (ns.CanWrite) { //开始异步写入 ns.BeginWrite( data, 0, data.Length, new AsyncCallback(SendCB), ns); } } catch (Exception e) { NetLogger.LogMsg("发送数据错误:" + e.Message, LogLevel.Error); } }
/// <summary> /// 开始接收网络数据 /// </summary> /// <param name="skt"></param> /// <param name="closeCB"></param> public void StartRcvData(Socket skt, Action closeCB) { try { this.skt = skt; this.closeCB = closeCB; //连接成功的回调 OnConnected(); NetPkg pack = new NetPkg(); //开始异步接收数据 skt.BeginReceive( pack.headBuff, 0, pack.headLen, SocketFlags.None, new AsyncCallback(RcvHeadData), pack); Console.WriteLine("接收数据:" + skt.ToString()); } catch (Exception e) { NetLogger.LogMsg("开始接收数据错误:" + e.Message, LogLevel.Error); } }
private void ProcessMsg(GameMsg msg) { NetLogger.LogMsg("处理数据:" + msg.chatMsg); if (msg.err != (int)ERR.None) { switch ((ERR)msg.err) { case ERR.None: NetLogger.LogMsg("err 111"); break; } return; } switch ((CMD)msg.cmd) { case CMD.HelloWorld: //接收到心跳包 刷新 if (ackMgr != null) { ackMgr.UpdateOneHeat(client.Client); } break; case CMD.Chat: NetLogger.LogMsg($"接收到聊天信息{msg.chatMsg}"); break; } }
void ClientConnectCB(IAsyncResult ar) { try { Socket clientSkt = skt.EndAccept(ar); T session = new T(); //存储会话 sessionLst.Add(session); //开始监听 session.StartRcvData(clientSkt, () => { if (sessionLst.Contains(session)) { //添加移除客户端的监听 RemoveSessionEvent?.Invoke(session); //从列表中移除 sessionLst.Remove(session); } }); //添加委托监听 AddSessionEvent?.Invoke(session); } catch (Exception e) { NetLogger.LogMsg("客户端 异步连接错误" + e.Message, LogLevel.Error); } skt.BeginAccept(new AsyncCallback(ClientConnectCB), skt); }
public void InitSvc() { client = new IClientSession <ClientSession, GameMsg>(); client.StartCreate(SrvCfg.srvIP, SrvCfg.srvPort); client.SetLog(true, (string msg, int lv) => { switch (lv) { case 0: msg = "Log:" + msg; NetLogger.LogMsg("消息 1:" + msg); break; case 1: msg = "Warn:" + msg; NetLogger.LogMsg("消息 2" + msg, LogLevel.Warn); break; case 2: msg = "Error:" + msg; NetLogger.LogMsg("消息 3:" + msg, LogLevel.Error); break; case 3: msg = "Info:" + msg; NetLogger.LogMsg(msg, LogLevel.Info); break; } }); NetLogger.LogMsg("Init NetSvc..."); }
/// <summary> /// 开始数据接收 /// </summary> /// <param name="socket"></param> /// <param name="close"></param> public void StartReciveData(Socket socket, Action close = null) { try { // 初始化赋值 skt = socket; OnDisReciveEvent += close; //回调开启连接事件 OnStartConnected(); OnStartConnectEvent?.Invoke(); //首先是接收头4个字节确认包长 //4可能太小了 pack.headBuff = new byte[4]; skt.BeginReceive( pack.headBuff, 0, 4, SocketFlags.None, ReciveHeadData, null); } catch (Exception e) { NetLogger.LogMsg($"开始接收数据错误:{e}", LogLevel.Error); } }
/// <summary> /// 发送网络数据 /// </summary> /// <param name="data"></param> public void SendMsg(byte[] data) { //创建流 准备异步写入发送 NetworkStream ns = null; try { //指定写入的socket ns = new NetworkStream(skt); //判断是否可以支持写入消息 if (ns.CanWrite) { //开始异步写入 ns.BeginWrite( data, 0, data.Length, SendDataAsync, ns); } } catch (Exception e) { NetLogger.LogMsg($"SendDataError:{e}", LogLevel.Error); } }
//异步回调 public override void ConnectAsync(IAsyncResult ar) { try { T client = new T(); //这里结束接收 获取刚刚连接的socket Socket sk = skt.EndAccept(ar); //开始监听 第二个是加入结束事件 client.StartReciveData(sk, () => { RemoveSession(client); RemoveSessionEvent?.Invoke(client); SessionList.Remove(client); }); //存储会话 SessionList.Add(client); AddSession(client); //添加委托监听 AddSessionEvent?.Invoke(client); //开始新一轮接收连接 skt.BeginAccept(ConnectAsync, null); } catch (Exception e) { NetLogger.LogMsg($"服务端连接回调错误:{e}", LogLevel.Error); skt?.BeginAccept(ConnectAsync, null); } }
void ClientConnectCB(IAsyncResult ar) { try { Socket clientSkt = skt.EndAccept(ar); T session = new T(); sessionLst.Add(session); session.StartRcvData(clientSkt, () => { if (sessionLst.Contains(session)) { sessionLst.Remove(session); } }); //开始为服务端添加上线和离线的监听事件 session.OnClientOffline += ClientOfflineEvent; session.OnClientOnline += ClientOnlineEvent; //开启扫描离线线程 Thread client = new Thread(new ThreadStart(ScanClientConnectCB)); client.IsBackground = true; client.Start(); NetLogger.LogMsg("开始扫描离线程序"); } catch (Exception e) { NetLogger.LogMsg(e.Message, LogLevel.Error); } skt.BeginAccept(new AsyncCallback(ClientConnectCB), skt); }
/// <summary> /// 接收包头数据 /// </summary> /// <param name="ar"></param> protected void ReciveHeadData(IAsyncResult ar) { try { //接收数据长度等于0意味着断开连接 //在断开的时候 异步会回调一次 直接调用EndReceive 会报错 if (skt == null) { return; } if (skt.Available == 0) { Clear(); return; } int len = skt.EndReceive(ar); if (len > 0) { pack.headIndex += len; //这里如果是小于4的就是凑不成 就是分包了 要继续接收 if (pack.headIndex < pack.headLen) { // skt.BeginReceive( pack.headBuff, pack.headIndex, pack.headLen - pack.headIndex, SocketFlags.None, ReciveHeadData, null); } //这里已经取出长度了 else { //赋值从那四个字节获取的byte[]的长度 pack.InitBodyBuff(); //进行真正的数据接收处理 skt.BeginReceive( pack.bodyBuff, 0, pack.bodyLen, SocketFlags.None, RcvBodyData, null); } } else { Clear(); } } catch (Exception e) { NetLogger.LogMsg($"接收:{e}", LogLevel.Error); } }
public void SendMsg(GameMsg msg) { if (client.Client != null) { client.Client.SendMsg(msg); } else { NetLogger.LogMsg("服务器未连接"); InitSvc(); } }
public void StartAsClient(string ip, int port) { try { skt.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port), new AsyncCallback(ServerConnectCB), skt); NetLogger.LogMsg("\n客户端启动成功!\n准备连接服务端......", LogLevel.Info); } catch (Exception e) { NetLogger.LogMsg(e.Message, LogLevel.Error); } }
/// <summary> /// 接收包体数据 /// </summary> /// <param name="ar"></param> protected void RcvBodyData(IAsyncResult ar) { try { //结束接收获取长度 int len = skt.EndReceive(ar); if (len > 0) { pack.bodyIndex += len; //这里是如果接收到的包长和原本获取到的长度小,就是分包了 需要再次进行接收剩下的 if (pack.bodyIndex < pack.bodyLen) { skt.BeginReceive( pack.bodyBuff, pack.bodyIndex, pack.headLen - pack.bodyIndex, SocketFlags.None, RcvBodyData, null); } //已经接完一组数据了 else { //这里就可以进行回调函数了 T msg = AnalysisMsg.DeSerialize <T>(pack.bodyBuff); OnReciveMsg(msg); OnReciveMsgEvent?.Invoke(msg); //开始新一轮的从上往下接收了 pack.ResetData(); pack.headBuff = new byte[4]; skt.BeginReceive( pack.headBuff, 0, 4, SocketFlags.None, ReciveHeadData, null); } } else { Clear(); } } catch (Exception e) { NetLogger.LogMsg($"ReciveDataError:{e}", LogLevel.Error); } }
public void StartAsServer(string ip, int port) { try { skt.Bind(new IPEndPoint(IPAddress.Parse(ip), port)); skt.Listen(backLog); skt.BeginAccept(new AsyncCallback(ClientConnectCB), skt); NetLogger.LogMsg("\nServer Start Success!\nWaiting for Connecting......", LogLevel.Info); } catch (Exception e) { NetLogger.LogMsg(e.Message, LogLevel.Error); } }
/// <summary> /// 发送网络数据后的回调 /// </summary> /// <param name="ar"></param> private void SendCB(IAsyncResult ar) { NetworkStream ns = (NetworkStream)ar.AsyncState; try { ns.EndWrite(ar); ns.Flush(); ns.Close(); } catch (Exception e) { NetLogger.LogMsg("发送数据回调错误:" + e.Message, LogLevel.Error); } }
public void StartAsServer(string ip, int port) { try { skt.Bind(new IPEndPoint(IPAddress.Parse(ip), port)); skt.Listen(backLog); //开始新一轮的接收连接 skt.BeginAccept(new AsyncCallback(ClientConnectCB), skt); NetLogger.LogMsg("\n服务端启动成功!\n等待连接中......", LogLevel.Info); } catch (Exception e) { NetLogger.LogMsg("服务端异步启动错误:" + e.Message, LogLevel.Error); } }
/// <summary> /// 接收包体数据 /// </summary> /// <param name="ar"></param> private void RcvBodyData(IAsyncResult ar) { try { NetPkg pack = (NetPkg)ar.AsyncState; int len = skt.EndReceive(ar); if (len > 0) { pack.bodyIndex += len; if (pack.bodyIndex < pack.bodyLen) { skt.BeginReceive(pack.bodyBuff, pack.bodyIndex, pack.headLen - pack.bodyIndex, SocketFlags.None, new AsyncCallback(RcvBodyData), pack ); } else { T msg = AnalysisMsg.DeSerialize <T>(pack.bodyBuff); OnReciveMsg(msg); //循环接收 pack.ResetData(); skt.BeginReceive( pack.headBuff, 0, pack.headLen, SocketFlags.None, new AsyncCallback(RcvHeadData), pack); } } else { OnDisConnected(); Clear(); } } catch (Exception e) { NetLogger.LogMsg("接收包体数据错误:" + e.Message, LogLevel.Error); } }
public override void StartCreate(string ip, int port) { try { //绑定地址 skt.Bind(new IPEndPoint(IPAddress.Parse(ip), port)); //设置监听数 skt.Listen(NetListen); //开始监听 skt.BeginAccept(ConnectAsync, null); NetLogger.LogMsg("建立服务器........"); } catch (Exception e) { NetLogger.LogMsg($"创建服务端连接错误:{e}", LogLevel.Error); } }
/// <summary> /// 这里是异步写入回调 /// </summary> /// <param name="ar"></param> protected void SendDataAsync(IAsyncResult ar) { //拿到写入时候的流 NetworkStream network = (NetworkStream)ar.AsyncState; try { //结束写入 就是发送了 然后进行关闭流 network.EndWrite(ar); network.Flush(); network.Close(); } catch (Exception e) { NetLogger.LogMsg("异步写入数据出错:" + e, LogLevel.Error); } }
void ServerConnectCB(IAsyncResult ar) { try { skt.EndConnect(ar); session = new T(); session.StartRcvData(skt, null); // 开启心跳线程 Thread server = new Thread(new ThreadStart(SendHeardBeatCB)); server.IsBackground = true; server.Start(); } catch (Exception e) { NetLogger.LogMsg(e.Message, LogLevel.Error); } }
public void StartSend() { { ackMgr = new AckMgr <ClientSession, NetAckMsg>().InitTimerEvent(send => { client.Client.SendMsg(new GameMsg { cmd = (int)CMD.HelloWorld }); }, obj => { NetLogger.LogMsg("心跳包超时准备断开连接"); if (obj != null) { NetLogger.LogMsg(ackMgr.ConnectDic[obj].Lostcount.ToString()); obj.Clear(); } }).StartTimer(); ackMgr.AddConnectDic(client.Client, null, 5, 5); }; }
public void RunEvent <A, B, C>(EventType type, A a, B b, C c) { List <IEvent> iEvents; if (!this.allEvents.TryGetValue(type, out iEvents)) { return; } foreach (IEvent iEvent in iEvents) { try { iEvent?.Handle(a, b, c); } catch (Exception e) { NetLogger.LogMsg(e.ToString()); } } }
/// <summary> /// 接收网络消息 /// </summary> /// <param name="msg"></param> protected virtual void OnReciveMsg(T msg) { //更新心跳包 NetLogger.LogMsg("接收网络消息.", LogLevel.Info); }
/// <summary> /// 开始扫描离线线程 /// </summary> public void ScanClientConnectCB() { session.ScanOffline(); NetLogger.LogMsg("开始扫描离线线程..."); }
/// <summary> /// 客户端上线提示 /// </summary> /// <param name="clientInfo"></param> public static void ClientOnlineEvent(ClientInfo clientInfo) { NetLogger.LogMsg(String.Format("客户端{0}上线,上线时间:\t{1}", clientInfo.ClientID, clientInfo.LastHeartbeatTime)); }
/// <summary> /// 客户端离线提示 /// </summary> /// <param name="clientInfo"></param> public virtual void ClientOfflineEvent(AckMsg clientInfo) { NetLogger.LogMsg($"客户端{sessionID}离线,离线时间:\t"); }
/// <summary> /// 客户端上线提示 /// </summary> /// <param name="clientInfo"></param> public virtual void ClientOnlineEvent(AckMsg clientInfo) { NetLogger.LogMsg($"客户端{sessionID}上线,上线时间:\t{clientInfo.lastHeartTime}"); }
/// <summary> /// 接收包头数据 /// </summary> /// <param name="ar"></param> private void RcvHeadData(IAsyncResult ar) { try { //避免断开连接时,异步回调调用EndReceive会报错 /*if (skt==null) * { * NetLogger.LogMsg("当前对应客户端不存在,直接返回"); * return; * }*/ if (skt == null) { return; } NetPkg pack = (NetPkg)ar.AsyncState; if (skt.Available == 0) { OnDisConnected(); Clear(); return; } NetLogger.LogMsg("开始结束异步读取"); int len = skt.EndReceive(ar); if (len > 0) { pack.headIndex += len; //如果是小于4的就是凑不成一个包头,就是要分包继续接收 if (pack.headIndex < pack.headLen) { //接收数据 skt.BeginReceive( pack.headBuff, pack.headIndex, pack.headLen - pack.headIndex, SocketFlags.None, new AsyncCallback(RcvHeadData), pack); } else { //设置byte[]的长度 pack.InitBodyBuff(); skt.BeginReceive(pack.bodyBuff, 0, pack.bodyLen, SocketFlags.None, new AsyncCallback(RcvBodyData), pack); } } else { OnDisConnected(); Clear(); } } catch (Exception e) { NetLogger.LogMsg("接收包头数据错误:" + e.Message, LogLevel.Error); } }
public void Init() { NetSvc.Instance.Init(); NetLogger.LogMsg("ServerRoot Init..."); }
/// <summary> /// 断开网络连接 /// </summary> protected virtual void OnDisConnected() { NetLogger.LogMsg($"客户端{sessionID}离线,离线时间:\t", LogLevel.Info); }