LitJson是一个开源项目,github地址为:
https://github.com/lbv/litjson/tree/v0.9.0
解决LitJson读取中文的问题:
http://blog.sina.com.cn/s/blog_6819cb9b01010l7h.html
LitJson下载(解决了读取中文的问题):
http://pan.baidu.com/s/1bn0qPMR
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
一.客户端
1.对消息进行枚举处理
public enum ModuleTypeEnum { Login, CharacterControl, }
public enum MessageTypeEnum { Login_Login, Login_Register, Character, }
public class LoginDTO { public string Account { get; set; } public string Password { get; set; } public LoginDTO() { } public LoginDTO(string account, string password) { Account = account; Password = password; } }
public class BoolDTO { public bool Value { get; set; } public BoolDTO() { } public BoolDTO(bool value) { Value = value; } }
using LitJson; public class SocketTool<T> { public static string ToJson(T o) { return JsonMapper.ToJson(o); } public static T ToObject(string s) { return JsonMapper.ToObject<T>(s); } }
using UnityEngine; using System.Collections; public class LoginHandler : SocketHandler { public override void Handle(SocketMessage sm) { if (sm.ModuleType == (int)(ModuleTypeEnum.Login)) { if (sm.MessageType == (int)(MessageTypeEnum.Login_Login)) { BoolDTO b = SocketTool<BoolDTO>.ToObject(sm.Message); if (b.Value) { Debug.Log("login success"); } else { Debug.Log("login fail"); } } } } }
private void Login() { if ((accountText.text != string.Empty) && (passwordText.text != string.Empty)) { LoginDTO l = new LoginDTO(accountText.text, passwordText.text); string s = SocketTool<LoginDTO>.ToJson(l); SocketMessage sm = new SocketMessage((int)ModuleTypeEnum.Login, (int)MessageTypeEnum.Login_Login, s); SocketSingletion.Instance.GetSocketClient().AsynSend(sm); } }
二.服务器端
1.接受消息
public static void HandleMessage(SocketClient sc, SocketMessage sm) { Console.WriteLine(sc.GetSocket().RemoteEndPoint.ToString() + " " + sm.Length + " " + sm.ModuleType + " " + sm.MessageType + " " + sm.Message); if (sm.ModuleType == (int)(ModuleTypeEnum.Login)) { if (sm.MessageType == (int)(MessageTypeEnum.Login_Login)) { BoolDTO b; LoginDTO l = SocketTool<LoginDTO>.ToObject(sm.Message); if(l.Account.Equals(l.Password)) { b = new BoolDTO(true); } else { b = new BoolDTO(false); } string s = SocketTool<BoolDTO>.ToJson(b); sc.AsynSend(new SocketMessage((int)ModuleTypeEnum.Login, (int)MessageTypeEnum.Login_Login, s)); } } }
源码下载:
http://pan.baidu.com/s/1gdUftLp