From 5ea975de93912313d8c424aba9940127b2ab7392 Mon Sep 17 00:00:00 2001 From: jarjin <2338894521@qq.com> Date: Thu, 9 Jul 2015 07:15:12 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=86=E7=BD=91=E7=BB=9C=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E5=99=A8=E8=BF=9B=E8=A1=8C=E8=A7=A3=E8=80=A6=EF=BC=8C=E4=BA=A4?= =?UTF-8?q?=E7=BB=99Command=E5=A4=84=E7=90=86=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Assets/Scripts/ConstDefine/NotiConst.cs | 11 +- .../Controller/Boostraps/BootstrapCommands.cs | 3 + .../Controller/Boostraps/BootstrapModels.cs | 4 +- .../Controller/Command/SocketCommand.cs | 19 ++ .../Command/SocketCommand.cs.meta} | 4 +- .../Controller/Command/StartUpCommand.cs | 6 +- Assets/Scripts/Manager/GameManager.cs | 2 - Assets/Scripts/Manager/NetworkManager.cs | 19 +- Assets/Scripts/Module/ChatMediator.cs | 42 --- Assets/Scripts/Module/ChatMediator.cs.meta | 10 - Assets/Scripts/Module/ChatProxy.cs | 33 --- Assets/Scripts/Module/ChatProxy.cs.meta | 10 - Assets/Scripts/Module/ChatWindow.cs | 41 --- Assets/Scripts/Module/SocketProxy.cs | 242 +++++++++++++++++ .../SocketProxy.cs.meta} | 0 Assets/Scripts/Network/SocketClient.cs | 255 ------------------ Assets/Scripts/Utility/LuaHelper.cs | 7 +- 17 files changed, 288 insertions(+), 420 deletions(-) create mode 100644 Assets/Scripts/Controller/Command/SocketCommand.cs rename Assets/Scripts/{Module/ChatWindow.cs.meta => Controller/Command/SocketCommand.cs.meta} (62%) delete mode 100644 Assets/Scripts/Module/ChatMediator.cs delete mode 100644 Assets/Scripts/Module/ChatMediator.cs.meta delete mode 100644 Assets/Scripts/Module/ChatProxy.cs delete mode 100644 Assets/Scripts/Module/ChatProxy.cs.meta delete mode 100644 Assets/Scripts/Module/ChatWindow.cs create mode 100644 Assets/Scripts/Module/SocketProxy.cs rename Assets/Scripts/{Network/SocketClient.cs.meta => Module/SocketProxy.cs.meta} (100%) delete mode 100644 Assets/Scripts/Network/SocketClient.cs diff --git a/Assets/Scripts/ConstDefine/NotiConst.cs b/Assets/Scripts/ConstDefine/NotiConst.cs index 912a647..d4e247d 100644 --- a/Assets/Scripts/ConstDefine/NotiConst.cs +++ b/Assets/Scripts/ConstDefine/NotiConst.cs @@ -3,13 +3,10 @@ public class NotiConst { - public const string START_UP = "StartUp"; //启动框架 - public const string INIT_LUA = "InitLua"; //初始化Lua - public const string RES_UPDATE = "ResUpdate"; //资源更新 - public const string RES_EXTRACT = "ResExract"; //资源解压 - - public const string SEND_INFO = "sendInfo"; //发送信息 - public const string RETURN_SEND_INFO = "returnSendInfo"; //发送信息(返回) + public const string START_UP = "StartUp"; //启动框架 + public const string DISPATCH_MESSAGE = "DispatchMessage"; //派发信息 + + public const string RETURN_SEND_INFO = "returnSendInfo"; //发送信息(返回) public const string SEND_PRIVATE_INFO = "sendPrivateInfo";//发送私聊信息 public const string RETURN_PUBLIC_INFO = "returnPublicInfo"; //返回世界聊天信息 diff --git a/Assets/Scripts/Controller/Boostraps/BootstrapCommands.cs b/Assets/Scripts/Controller/Boostraps/BootstrapCommands.cs index f6be5f9..81b1d46 100644 --- a/Assets/Scripts/Controller/Boostraps/BootstrapCommands.cs +++ b/Assets/Scripts/Controller/Boostraps/BootstrapCommands.cs @@ -15,6 +15,9 @@ public class BootstrapCommands : SimpleCommand { /// /// public override void Execute(INotification notification) { + //-----------------关联命令----------------------- + Facade.RegisterCommand(NotiConst.DISPATCH_MESSAGE, typeof(SocketCommand)); + //-----------------初始化管理器----------------------- Facade.AddManager(ManagerName.Lua, new LuaScriptMgr()); diff --git a/Assets/Scripts/Controller/Boostraps/BootstrapModels.cs b/Assets/Scripts/Controller/Boostraps/BootstrapModels.cs index 0dcdc48..8dfb8f8 100644 --- a/Assets/Scripts/Controller/Boostraps/BootstrapModels.cs +++ b/Assets/Scripts/Controller/Boostraps/BootstrapModels.cs @@ -3,11 +3,9 @@ using PureMVC.Patterns; using PureMVC.Interfaces; -/** - * 注册Command ,建立 Command 与Notification 之间的映射 - */ public class BootstrapModels : SimpleCommand { public override void Execute(INotification notification) { + Facade.RegisterProxy(new SocketProxy()); } } diff --git a/Assets/Scripts/Controller/Command/SocketCommand.cs b/Assets/Scripts/Controller/Command/SocketCommand.cs new file mode 100644 index 0000000..c5cdb2f --- /dev/null +++ b/Assets/Scripts/Controller/Command/SocketCommand.cs @@ -0,0 +1,19 @@ +using UnityEngine; +using System.Collections; +using PureMVC.Patterns; +using PureMVC.Interfaces; +using System.Collections.Generic; +using SimpleFramework; + +public class SocketCommand : SimpleCommand { + + public override void Execute(INotification notification) { + object body = notification.Body; + if (body == null) return; + + KeyValuePair message = (KeyValuePair)body; + switch (message.Key) { + default: Util.CallMethod("Network", "OnSocket", message.Key, message.Value); break; + } + } +} diff --git a/Assets/Scripts/Module/ChatWindow.cs.meta b/Assets/Scripts/Controller/Command/SocketCommand.cs.meta similarity index 62% rename from Assets/Scripts/Module/ChatWindow.cs.meta rename to Assets/Scripts/Controller/Command/SocketCommand.cs.meta index 3c46882..f544f8d 100644 --- a/Assets/Scripts/Module/ChatWindow.cs.meta +++ b/Assets/Scripts/Controller/Command/SocketCommand.cs.meta @@ -1,10 +1,8 @@ fileFormatVersion: 2 -guid: ad87870980f15534193dfd8da9a1ea79 +guid: 2384cc1ec84c1674793c84b948d36fe8 MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/Controller/Command/StartUpCommand.cs b/Assets/Scripts/Controller/Command/StartUpCommand.cs index cab82ad..44be694 100644 --- a/Assets/Scripts/Controller/Command/StartUpCommand.cs +++ b/Assets/Scripts/Controller/Command/StartUpCommand.cs @@ -21,12 +21,12 @@ protected override void InitializeMacroCommand() { EditorApplication.isPlaying = false; return; } - //BootstrapCommands - AddSubCommand(typeof(BootstrapCommands)); - //BootstrapModels AddSubCommand(typeof(BootstrapModels)); + //BootstrapCommands + AddSubCommand(typeof(BootstrapCommands)); + //BootstrapViewMediators AddSubCommand(typeof(BootstrapViewMediators)); } diff --git a/Assets/Scripts/Manager/GameManager.cs b/Assets/Scripts/Manager/GameManager.cs index 005a2f5..5599967 100644 --- a/Assets/Scripts/Manager/GameManager.cs +++ b/Assets/Scripts/Manager/GameManager.cs @@ -33,8 +33,6 @@ void Init() { ZipConstants.DefaultCodePage = 65001; Screen.sleepTimeout = SleepTimeout.NeverSleep; Application.targetFrameRate = AppConst.GameFrameRate; - - //facade.SendNotification(""); } /// diff --git a/Assets/Scripts/Manager/NetworkManager.cs b/Assets/Scripts/Manager/NetworkManager.cs index 60de966..ebeb273 100644 --- a/Assets/Scripts/Manager/NetworkManager.cs +++ b/Assets/Scripts/Manager/NetworkManager.cs @@ -6,14 +6,22 @@ namespace SimpleFramework.Manager { public class NetworkManager : BehaviourBase { - private static Queue> sEvents = new Queue>(); + private SocketProxy socket; + static Queue> sEvents = new Queue>(); + + SocketProxy SocketClient { + get { + if (socket == null) + socket = facade.RetrieveProxy(SocketProxy.NAME) as SocketProxy; + return socket; + } + } void Awake() { Init(); } void Init() { - Util.Add(gameObject); } public void OnInit() { @@ -36,13 +44,14 @@ public static void AddEvent(int _event, ByteBuffer data) { sEvents.Enqueue(new KeyValuePair(_event, data)); } + /// + /// Commandﲻķ˭ + /// void Update() { if (sEvents.Count > 0) { while (sEvents.Count > 0) { KeyValuePair _event = sEvents.Dequeue(); - switch (_event.Key) { - default: CallMethod("OnSocket", _event.Key, _event.Value); break; - } + facade.SendNotification(NotiConst.DISPATCH_MESSAGE, _event); } } } diff --git a/Assets/Scripts/Module/ChatMediator.cs b/Assets/Scripts/Module/ChatMediator.cs deleted file mode 100644 index b919b21..0000000 --- a/Assets/Scripts/Module/ChatMediator.cs +++ /dev/null @@ -1,42 +0,0 @@ -using PureMVC.Patterns; -using PureMVC.Interfaces; -using System.Collections.Generic; -using UnityEngine; - -public class ChatMediator : Mediator -{ - public const string NAME = "chatMediator"; - public ChatMediator(object viewComponent) : base(NAME, viewComponent) - { - } - - public ChatWindow getView() - { - return ViewComponent as ChatWindow; - } - - override public IList ListNotificationInterests() - { - return new List() - { - NotiConst.RETURN_SEND_INFO, - NotiConst.RETURN_PUBLIC_INFO, - }; - } - - override public void HandleNotification(INotification notification) - { - string name = notification.Name; - object body = notification.Body; - switch (name) - { - case NotiConst.RETURN_SEND_INFO: - Debug.Log("Mediator接收来自Proxy的服务端返回" + body.ToString()); - getView().returnServerHander(body.ToString()); - break; - case NotiConst.RETURN_PUBLIC_INFO: - getView().returnPrivateMsg(body); - break; - } - } -} diff --git a/Assets/Scripts/Module/ChatMediator.cs.meta b/Assets/Scripts/Module/ChatMediator.cs.meta deleted file mode 100644 index a05873c..0000000 --- a/Assets/Scripts/Module/ChatMediator.cs.meta +++ /dev/null @@ -1,10 +0,0 @@ -fileFormatVersion: 2 -guid: 69bce36ef77481a418cc0e79eb28fd7b -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/Module/ChatProxy.cs b/Assets/Scripts/Module/ChatProxy.cs deleted file mode 100644 index fccae7b..0000000 --- a/Assets/Scripts/Module/ChatProxy.cs +++ /dev/null @@ -1,33 +0,0 @@ -using PureMVC.Patterns; -using UnityEngine; -using System.Collections.Generic; - -public class ChatProxy : Proxy -{ - public static string NAME = "ChatProxy"; - public static ChatProxy instances; - public ChatProxy() : base(NAME) - { - instances = this; - } - - //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~发送信息~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - public void sendChatMsg(string str) - { - Debug.Log("Proxy接收到Command的消息:" + str); - Debug.Log("发送消息给服务器"); //模拟 - Debug.Log("等待服务器返回"); - Debug.Log("服务器返回信息啦"); - returnSendMsg("Server:" + str); - } - - /// - /// 发送私聊信息 - /// - /// - public void returnSendMsg(string str) - { - Debug.Log("Proxy发送服务端返回信息:" + str); - SendNotification(NotiConst.RETURN_SEND_INFO, str); - } -} diff --git a/Assets/Scripts/Module/ChatProxy.cs.meta b/Assets/Scripts/Module/ChatProxy.cs.meta deleted file mode 100644 index d762ed7..0000000 --- a/Assets/Scripts/Module/ChatProxy.cs.meta +++ /dev/null @@ -1,10 +0,0 @@ -fileFormatVersion: 2 -guid: 67fc42d4c5c0f834d8495f580060a59c -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Scripts/Module/ChatWindow.cs b/Assets/Scripts/Module/ChatWindow.cs deleted file mode 100644 index 1620d5c..0000000 --- a/Assets/Scripts/Module/ChatWindow.cs +++ /dev/null @@ -1,41 +0,0 @@ -using UnityEngine; -using System.Collections; - -public class ChatWindow : MonoBehaviour -{ - public UITextList textList; - public UIInput mInput; - - void Start() - { - AppFacade.Instance.StartUp(); //启动 - AppFacade.Instance.RegisterProxy(new ChatProxy()); //注册聊天委托 - AppFacade.Instance.RegisterMediator(new ChatMediator(this)); //注册Mediator - } - - public void sendMessageHandler() - { - if (textList != null) - { - string text = NGUIText.StripSymbols(mInput.value); - if (!string.IsNullOrEmpty(text)) - { - mInput.value = ""; - mInput.isSelected = false; - Debug.Log("UI发送聊天信息:" + text); - AppFacade.Instance.SendNotification(NotiConst.SEND_INFO, text); - } - } - } - - public void returnServerHander(string str) - { - Debug.Log("来自Mediator的返回,刷新UI界面"); - textList.Add(str); - } - - public void returnPrivateMsg(object obj) - { - Debug.Log(obj); - } -} diff --git a/Assets/Scripts/Module/SocketProxy.cs b/Assets/Scripts/Module/SocketProxy.cs new file mode 100644 index 0000000..8672f82 --- /dev/null +++ b/Assets/Scripts/Module/SocketProxy.cs @@ -0,0 +1,242 @@ +using UnityEngine; +using System; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Collections; +using System.Collections.Generic; +using SimpleFramework.Manager; +using PureMVC.Patterns; +using SimpleFramework; + +public enum DisType { + Exception, + Disconnect, +} + +public class SocketProxy : Proxy { + private TcpClient client = null; + private NetworkStream outStream = null; + private MemoryStream memStream; + private BinaryReader reader; + + private const int MAX_READ = 8192; + private byte[] byteBuffer = new byte[MAX_READ]; + + public static bool loggedIn = false; + public static string NAME = "SocketProxy"; + public static SocketProxy instances; + + // Use this for initialization + public SocketProxy() : base(NAME) { + instances = this; + } + + /// + /// 注册代理 + /// + public override void OnRegister() { + memStream = new MemoryStream(); + reader = new BinaryReader(memStream); + } + + /// + /// 移除代理 + /// + public override void OnRemove() { + this.Close(); + reader.Close(); + memStream.Close(); + } + + /// + /// 连接服务器 + /// + void ConnectServer(string host, int port) { + client = null; + client = new TcpClient(); + client.SendTimeout = 1000; + client.ReceiveTimeout = 1000; + client.NoDelay = true; + try { + client.BeginConnect(host, port, new AsyncCallback(OnConnect), null); + } catch (Exception e) { + Close(); Debug.LogError(e.Message); + } + } + + /// + /// 连接上服务器 + /// + void OnConnect(IAsyncResult asr) { + outStream = client.GetStream(); + client.GetStream().BeginRead(byteBuffer, 0, MAX_READ, new AsyncCallback(OnRead), null); + NetworkManager.AddEvent(Protocal.Connect, new ByteBuffer()); + } + + /// + /// 写数据 + /// + void WriteMessage(byte[] message) { + MemoryStream ms = null; + using (ms = new MemoryStream()) { + ms.Position = 0; + BinaryWriter writer = new BinaryWriter(ms); + ushort msglen = (ushort)message.Length; + writer.Write(msglen); + writer.Write(message); + writer.Flush(); + if (client != null && client.Connected) { + //NetworkStream stream = client.GetStream(); + byte[] payload = ms.ToArray(); + outStream.BeginWrite(payload, 0, payload.Length, new AsyncCallback(OnWrite), null); + } else { + Debug.LogError("client.connected----->>false"); + } + } + } + + /// + /// 读取消息 + /// + void OnRead(IAsyncResult asr) { + int bytesRead = 0; + try { + lock (client.GetStream()) { //读取字节流到缓冲区 + bytesRead = client.GetStream().EndRead(asr); + } + if (bytesRead < 1) { //包尺寸有问题,断线处理 + OnDisconnected(DisType.Disconnect, "bytesRead < 1"); + return; + } + OnReceive(byteBuffer, bytesRead); //分析数据包内容,抛给逻辑层 + lock (client.GetStream()) { //分析完,再次监听服务器发过来的新消息 + Array.Clear(byteBuffer, 0, byteBuffer.Length); //清空数组 + client.GetStream().BeginRead(byteBuffer, 0, MAX_READ, new AsyncCallback(OnRead), null); + } + } catch (Exception ex) { + //PrintBytes(); + OnDisconnected(DisType.Exception, ex.Message); + } + } + + /// + /// 丢失链接 + /// + void OnDisconnected(DisType dis, string msg) { + Close(); //关掉客户端链接 + int protocal = dis == DisType.Exception ? + Protocal.Exception : Protocal.Disconnect; + + ByteBuffer buffer = new ByteBuffer(); + buffer.WriteShort((ushort)protocal); + NetworkManager.AddEvent(protocal, buffer); + Debug.LogError("Connection was closed by the server:>" + msg + " Distype:>" + dis); + } + + /// + /// 打印字节 + /// + /// + void PrintBytes() { + string returnStr = string.Empty; + for (int i = 0; i < byteBuffer.Length; i++) { + returnStr += byteBuffer[i].ToString("X2"); + } + Debug.LogError(returnStr); + } + + /// + /// 向链接写入数据流 + /// + void OnWrite(IAsyncResult r) { + try { + outStream.EndWrite(r); + } catch (Exception ex) { + Debug.LogError("OnWrite--->>>" + ex.Message); + } + } + + /// + /// 接收到消息 + /// + void OnReceive(byte[] bytes, int length) { + memStream.Seek(0, SeekOrigin.End); + memStream.Write(bytes, 0, length); + //Reset to beginning + memStream.Seek(0, SeekOrigin.Begin); + while (RemainingBytes() > 2) { + ushort messageLen = reader.ReadUInt16(); + if (RemainingBytes() >= messageLen) { + MemoryStream ms = new MemoryStream(); + BinaryWriter writer = new BinaryWriter(ms); + writer.Write(reader.ReadBytes(messageLen)); + ms.Seek(0, SeekOrigin.Begin); + OnReceivedMessage(ms); + } else { + //Back up the position two bytes + memStream.Position = memStream.Position - 2; + break; + } + } + //Create a new stream with any leftover bytes + byte[] leftover = reader.ReadBytes((int)RemainingBytes()); + memStream.SetLength(0); //Clear + memStream.Write(leftover, 0, leftover.Length); + } + + /// + /// 剩余的字节 + /// + private long RemainingBytes() { + return memStream.Length - memStream.Position; + } + + /// + /// 接收到消息 + /// + /// + void OnReceivedMessage(MemoryStream ms) { + BinaryReader r = new BinaryReader(ms); + byte[] message = r.ReadBytes((int)(ms.Length - ms.Position)); + //int msglen = message.Length; + + ByteBuffer buffer = new ByteBuffer(message); + int mainId = buffer.ReadShort(); + NetworkManager.AddEvent(mainId, buffer); + } + + + /// + /// 会话发送 + /// + void SessionSend(byte[] bytes) { + WriteMessage(bytes); + } + + /// + /// 关闭链接 + /// + public void Close() { + if (client != null) { + if (client.Connected) client.Close(); + client = null; + } + loggedIn = false; + } + + /// + /// 发送连接请求 + /// + public void SendConnect() { + ConnectServer(AppConst.SocketAddress, AppConst.SocketPort); + } + + /// + /// 发送消息 + /// + public void SendMessage(ByteBuffer buffer) { + SessionSend(buffer.ToBytes()); + buffer.Close(); + } +} diff --git a/Assets/Scripts/Network/SocketClient.cs.meta b/Assets/Scripts/Module/SocketProxy.cs.meta similarity index 100% rename from Assets/Scripts/Network/SocketClient.cs.meta rename to Assets/Scripts/Module/SocketProxy.cs.meta diff --git a/Assets/Scripts/Network/SocketClient.cs b/Assets/Scripts/Network/SocketClient.cs deleted file mode 100644 index b28c2ed..0000000 --- a/Assets/Scripts/Network/SocketClient.cs +++ /dev/null @@ -1,255 +0,0 @@ -using UnityEngine; -using System; -using System.IO; -using System.Net; -using System.Net.Sockets; -using System.Collections; -using System.Collections.Generic; -using SimpleFramework.Manager; - -namespace SimpleFramework { - public enum DisType { - Exception, - Disconnect, - } - - public enum NetActionType { - Connect, - Message, - Logout - } - - public class SocketClient : MonoBehaviour { - private TcpClient client = null; - private NetworkStream outStream = null; - private MemoryStream memStream; - private BinaryReader reader; - private const int MAX_READ = 8192; - private byte[] byteBuffer = new byte[MAX_READ]; - - public static bool loggedIn = false; - private static Queue> _events = new Queue>(); - - // Use this for initialization - void Awake() { - memStream = new MemoryStream(); - reader = new BinaryReader(memStream); - } - - /// - /// 消息循环 - /// - void Update() { - while (_events.Count > 0) { - KeyValuePair _event = _events.Dequeue(); - switch (_event.Key) { - case NetActionType.Connect: - ConnectServer(AppConst.SocketAddress, AppConst.SocketPort); - break; - case NetActionType.Message: - SessionSend(_event.Value.ToBytes()); - break; - case NetActionType.Logout: Close(); break; - } - if (_event.Value != null) _event.Value.Close(); - } - } - - /// - /// 连接服务器 - /// - void ConnectServer(string host, int port) { - client = null; - client = new TcpClient(); - client.SendTimeout = 1000; - client.ReceiveTimeout = 1000; - client.NoDelay = true; - try { - client.BeginConnect(host, port, new AsyncCallback(OnConnect), null); - } catch (Exception e) { - Close(); Debug.LogError(e.Message); - } - } - - /// - /// 连接上服务器 - /// - void OnConnect(IAsyncResult asr) { - outStream = client.GetStream(); - client.GetStream().BeginRead(byteBuffer, 0, MAX_READ, new AsyncCallback(OnRead), null); - NetworkManager.AddEvent(Protocal.Connect, new ByteBuffer()); - } - - /// - /// 写数据 - /// - void WriteMessage(byte[] message) { - MemoryStream ms = null; - using (ms = new MemoryStream()) { - ms.Position = 0; - BinaryWriter writer = new BinaryWriter(ms); - ushort msglen = (ushort)message.Length; - writer.Write(msglen); - writer.Write(message); - writer.Flush(); - if (client != null && client.Connected) { - //NetworkStream stream = client.GetStream(); - byte[] payload = ms.ToArray(); - outStream.BeginWrite(payload, 0, payload.Length, new AsyncCallback(OnWrite), null); - } else { - Debug.LogError("client.connected----->>false"); - } - } - } - - /// - /// 读取消息 - /// - void OnRead(IAsyncResult asr) { - int bytesRead = 0; - try { - lock (client.GetStream()) { //读取字节流到缓冲区 - bytesRead = client.GetStream().EndRead(asr); - } - if (bytesRead < 1) { //包尺寸有问题,断线处理 - OnDisconnected(DisType.Disconnect, "bytesRead < 1"); - return; - } - OnReceive(byteBuffer, bytesRead); //分析数据包内容,抛给逻辑层 - lock (client.GetStream()) { //分析完,再次监听服务器发过来的新消息 - Array.Clear(byteBuffer, 0, byteBuffer.Length); //清空数组 - client.GetStream().BeginRead(byteBuffer, 0, MAX_READ, new AsyncCallback(OnRead), null); - } - } catch (Exception ex) { - //PrintBytes(); - OnDisconnected(DisType.Exception, ex.Message); - } - } - - /// - /// 丢失链接 - /// - void OnDisconnected(DisType dis, string msg) { - Close(); //关掉客户端链接 - int protocal = dis == DisType.Exception ? - Protocal.Exception : Protocal.Disconnect; - - ByteBuffer buffer = new ByteBuffer(); - buffer.WriteShort((ushort)protocal); - NetworkManager.AddEvent(protocal, buffer); - Debug.LogError("Connection was closed by the server:>" + msg + " Distype:>" + dis); - } - - /// - /// 打印字节 - /// - /// - void PrintBytes() { - string returnStr = string.Empty; - for (int i = 0; i < byteBuffer.Length; i++) { - returnStr += byteBuffer[i].ToString("X2"); - } - Debug.LogError(returnStr); - } - - /// - /// 向链接写入数据流 - /// - void OnWrite(IAsyncResult r) { - try { - outStream.EndWrite(r); - } catch (Exception ex) { - Debug.LogError("OnWrite--->>>" + ex.Message); - } - } - - /// - /// 接收到消息 - /// - void OnReceive(byte[] bytes, int length) { - memStream.Seek(0, SeekOrigin.End); - memStream.Write(bytes, 0, length); - //Reset to beginning - memStream.Seek(0, SeekOrigin.Begin); - while (RemainingBytes() > 2) { - ushort messageLen = reader.ReadUInt16(); - if (RemainingBytes() >= messageLen) { - MemoryStream ms = new MemoryStream(); - BinaryWriter writer = new BinaryWriter(ms); - writer.Write(reader.ReadBytes(messageLen)); - ms.Seek(0, SeekOrigin.Begin); - OnReceivedMessage(ms); - } else { - //Back up the position two bytes - memStream.Position = memStream.Position - 2; - break; - } - } - //Create a new stream with any leftover bytes - byte[] leftover = reader.ReadBytes((int)RemainingBytes()); - memStream.SetLength(0); //Clear - memStream.Write(leftover, 0, leftover.Length); - } - - /// - /// 剩余的字节 - /// - private long RemainingBytes() { - return memStream.Length - memStream.Position; - } - - /// - /// 接收到消息 - /// - /// - void OnReceivedMessage(MemoryStream ms) { - BinaryReader r = new BinaryReader(ms); - byte[] message = r.ReadBytes((int)(ms.Length - ms.Position)); - //int msglen = message.Length; - - ByteBuffer buffer = new ByteBuffer(message); - int mainId = buffer.ReadShort(); - NetworkManager.AddEvent(mainId, buffer); - } - - - /// - /// 会话发送 - /// - void SessionSend(byte[] bytes) { - WriteMessage(bytes); - } - - /// - /// 关闭链接 - /// - void Close() { - if (client != null) { - if (client.Connected) client.Close(); - client = null; - } - loggedIn = false; - } - - /// - /// 登出 - /// - public static void Logout() { - _events.Enqueue(new KeyValuePair(NetActionType.Logout, null)); - } - - /// - /// 发送连接请求 - /// - public static void SendConnect() { - _events.Enqueue(new KeyValuePair(NetActionType.Connect, null)); - } - - /// - /// 发送消息 - /// - public static void SendMessage(ByteBuffer buffer) { - _events.Enqueue(new KeyValuePair(NetActionType.Message, buffer)); - } - } -} \ No newline at end of file diff --git a/Assets/Scripts/Utility/LuaHelper.cs b/Assets/Scripts/Utility/LuaHelper.cs index 1965348..9f0006f 100644 --- a/Assets/Scripts/Utility/LuaHelper.cs +++ b/Assets/Scripts/Utility/LuaHelper.cs @@ -1,9 +1,4 @@ -/************************************************* -author:ricky pu -data:2014.4.12 -email:32145628@qq.com -**********************************************/ -using UnityEngine; +using UnityEngine; using System.Collections.Generic; using System.Reflection; using LuaInterface;