// 接收体消息 void ReceiveBody(IAsyncResult ar) { try { // 返回网络上接收的数据长度 int read = socket.EndReceive(ar); // 已断开连接 if (read < 1) { // 通知丢失连接 handler.OnLost(rPacket); return; } rPacket.readLength += read; // 消息体必须读满指定的长度 if (rPacket.readLength < rPacket.bodyLenght) { socket.BeginReceive(rPacket.bytes, NetPacket.headerLength + rPacket.readLength, rPacket.bodyLenght - rPacket.readLength, SocketFlags.None, new AsyncCallback(ReceiveBody), rPacket); } else { // 将消息传入到逻辑处理队列 string msgName = ""; rPacket.BeginRead(out msgName); HandlerMeta meta = HandlerDispatch.Dispatch.getMeta(msgName); if (meta != null) { object msg = rPacket.ReadObject(meta.msgType); MsgDispatch.Dispatch.AddMsg(msg); } else { Debug.LogError("没有找到对应的 handler " + msgName); } // 下一个读取 rPacket.Reset(); socket.BeginReceive(rPacket.bytes, 0, NetPacket.headerLength, SocketFlags.None, new AsyncCallback(ReceiveHeader), rPacket); } } catch (Exception ex) { handler.OnError("ReceiveBody", ex); } }
public void Update() { object msg = null; for (msg = GetMsg(); msg != null;) { HandlerMeta meta = HandlerDispatch.Dispatch.getMeta(msg.GetType().Name); try { meta.method.Invoke(meta.instance, new object[] { msg }); } catch (Exception ex) { Debug.LogError("执行 handler 出错 " + ex.Message); } msg = GetMsg(); } }