├── .gitignore ├── .vs └── fastPomeloUnity │ └── v14 │ └── .suo ├── Assets ├── Resource.meta ├── Resource │ ├── Materials.meta │ ├── Materials │ │ ├── earth.mat │ │ └── earth.mat.meta │ ├── earth.jpg │ └── earth.jpg.meta ├── Scenes.meta ├── Scenes │ ├── boot.unity │ └── boot.unity.meta ├── Scripts.meta └── Scripts │ ├── Game.cs │ ├── Game.cs.meta │ ├── Main.cs │ ├── Main.cs.meta │ ├── Networks.meta │ ├── Networks │ ├── BroadcastFact.cs │ ├── BroadcastFact.cs.meta │ ├── CallbackFact.cs │ ├── CallbackFact.cs.meta │ ├── Handlers.meta │ ├── Handlers │ │ ├── ConnectorHandler.cs │ │ ├── ConnectorHandler.cs.meta │ │ ├── GameHandler.cs │ │ └── GameHandler.cs.meta │ ├── NetworkMgr.cs │ ├── NetworkMgr.cs.meta │ ├── Routes.cs │ ├── Routes.cs.meta │ ├── Senders.meta │ ├── Senders │ │ ├── ConnectorSender.cs │ │ ├── ConnectorSender.cs.meta │ │ ├── GameSender.cs │ │ └── GameSender.cs.meta │ ├── pomelo.meta │ └── pomelo │ │ ├── client.meta │ │ ├── client │ │ ├── EventManager.cs │ │ ├── EventManager.cs.meta │ │ ├── PomeloClient.cs │ │ ├── PomeloClient.cs.meta │ │ ├── PomeloClient.cs.old │ │ ├── PomeloClient.cs.old.meta │ │ ├── test.meta │ │ └── test │ │ │ ├── ClientTest.cs │ │ │ └── ClientTest.cs.meta │ │ ├── lib.meta │ │ ├── lib │ │ ├── SimpleJson.dll │ │ └── SimpleJson.dll.meta │ │ ├── protobuf.meta │ │ ├── protobuf │ │ ├── Decoder.cs │ │ ├── Decoder.cs.meta │ │ ├── Encoder.cs │ │ ├── Encoder.cs.meta │ │ ├── MsgDecoder.cs │ │ ├── MsgDecoder.cs.meta │ │ ├── MsgEncoder.cs │ │ ├── MsgEncoder.cs.meta │ │ ├── Protobuf.cs │ │ ├── Protobuf.cs.meta │ │ ├── test.meta │ │ ├── test │ │ │ ├── CodecTest.cs │ │ │ ├── CodecTest.cs.meta │ │ │ ├── ProtobufTest.cs │ │ │ └── ProtobufTest.cs.meta │ │ ├── util.meta │ │ └── util │ │ │ ├── Util.cs │ │ │ └── Util.cs.meta │ │ ├── protocol.meta │ │ ├── protocol │ │ ├── HandShakeService.cs │ │ ├── HandShakeService.cs.meta │ │ ├── HeartBeatService.cs │ │ ├── HeartBeatService.cs.meta │ │ ├── Message.cs │ │ ├── Message.cs.meta │ │ ├── MessageProtocol.cs │ │ ├── MessageProtocol.cs.meta │ │ ├── MessageType.cs │ │ ├── MessageType.cs.meta │ │ ├── Package.cs │ │ ├── Package.cs.meta │ │ ├── PackageProtocol.cs │ │ ├── PackageProtocol.cs.meta │ │ ├── PackageTypes.cs │ │ ├── PackageTypes.cs.meta │ │ ├── Protocol.cs │ │ ├── Protocol.cs.meta │ │ ├── ProtocolState.cs │ │ └── ProtocolState.cs.meta │ │ ├── transport.meta │ │ └── transport │ │ ├── TransportState.cs │ │ ├── TransportState.cs.meta │ │ ├── Transporter.cs │ │ ├── Transporter.cs.meta │ │ ├── test.meta │ │ └── test │ │ ├── TransportTest.cs │ │ └── TransportTest.cs.meta │ ├── RoundBall.cs │ ├── RoundBall.cs.meta │ ├── UILogic.meta │ └── UILogic │ ├── ButtonClick.cs │ └── ButtonClick.cs.meta ├── ProjectSettings ├── AudioManager.asset ├── ClusterInputManager.asset ├── DynamicsManager.asset ├── EditorBuildSettings.asset ├── EditorSettings.asset ├── GraphicsSettings.asset ├── InputManager.asset ├── NavMeshAreas.asset ├── NetworkManager.asset ├── Physics2DSettings.asset ├── ProjectSettings.asset ├── ProjectVersion.txt ├── QualitySettings.asset ├── TagManager.asset ├── TimeManager.asset ├── UnityAdsSettings.asset └── UnityConnectSettings.asset ├── README.md ├── fastPomeloUnity.CSharp.csproj └── fastPomeloUnity.sln /.gitignore: -------------------------------------------------------------------------------- 1 | Library/ 2 | Temp/ 3 | -------------------------------------------------------------------------------- /.vs/fastPomeloUnity/v14/.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/.vs/fastPomeloUnity/v14/.suo -------------------------------------------------------------------------------- /Assets/Resource.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 202def2448ad72549b7bfb0636101453 3 | folderAsset: yes 4 | timeCreated: 1473315421 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Resource/Materials.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: cfec84540c0278541834fa4ff9ee9f33 3 | folderAsset: yes 4 | timeCreated: 1473315833 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Resource/Materials/earth.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/Assets/Resource/Materials/earth.mat -------------------------------------------------------------------------------- /Assets/Resource/Materials/earth.mat.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 1bfa685961c2aeb469378119cb7ecfdd 3 | timeCreated: 1473315833 4 | licenseType: Pro 5 | NativeFormatImporter: 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Assets/Resource/earth.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/Assets/Resource/earth.jpg -------------------------------------------------------------------------------- /Assets/Resource/earth.jpg.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 45c957cf03a96dc4eb546d5d769257c6 3 | timeCreated: 1473315807 4 | licenseType: Pro 5 | TextureImporter: 6 | fileIDToRecycleName: {} 7 | serializedVersion: 2 8 | mipmaps: 9 | mipMapMode: 0 10 | enableMipMap: 1 11 | linearTexture: 0 12 | correctGamma: 0 13 | fadeOut: 0 14 | borderMipMap: 0 15 | mipMapFadeDistanceStart: 1 16 | mipMapFadeDistanceEnd: 3 17 | bumpmap: 18 | convertToNormalMap: 0 19 | externalNormalMap: 0 20 | heightScale: 0.25 21 | normalMapFilter: 0 22 | isReadable: 0 23 | grayScaleToAlpha: 0 24 | generateCubemap: 0 25 | cubemapConvolution: 0 26 | cubemapConvolutionSteps: 7 27 | cubemapConvolutionExponent: 1.5 28 | seamlessCubemap: 0 29 | textureFormat: -1 30 | maxTextureSize: 2048 31 | textureSettings: 32 | filterMode: -1 33 | aniso: 16 34 | mipBias: -1 35 | wrapMode: 1 36 | nPOTScale: 1 37 | lightmap: 0 38 | rGBM: 0 39 | compressionQuality: 50 40 | allowsAlphaSplitting: 0 41 | spriteMode: 0 42 | spriteExtrude: 1 43 | spriteMeshType: 1 44 | alignment: 0 45 | spritePivot: {x: 0.5, y: 0.5} 46 | spriteBorder: {x: 0, y: 0, z: 0, w: 0} 47 | spritePixelsToUnits: 100 48 | alphaIsTransparency: 0 49 | textureType: 0 50 | buildTargetSettings: [] 51 | spriteSheet: 52 | serializedVersion: 2 53 | sprites: [] 54 | outline: [] 55 | spritePackingTag: 56 | userData: 57 | assetBundleName: 58 | assetBundleVariant: 59 | -------------------------------------------------------------------------------- /Assets/Scenes.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 13a4348b5d8e9904a8fd1908571013bb 3 | folderAsset: yes 4 | timeCreated: 1473315376 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scenes/boot.unity: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/Assets/Scenes/boot.unity -------------------------------------------------------------------------------- /Assets/Scenes/boot.unity.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: a9add9a360fda794280f0c16cd7fad07 3 | timeCreated: 1473315382 4 | licenseType: Pro 5 | DefaultImporter: 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Assets/Scripts.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 2e6cf3d31d8d92f49a9f9dcea49fab55 3 | folderAsset: yes 4 | timeCreated: 1473315391 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Game.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class Game { 5 | NetworkMgr networkMgr; 6 | 7 | public Game() { 8 | } 9 | 10 | public void init() { 11 | networkMgr = NetworkMgr.getInstance(); 12 | 13 | } 14 | 15 | // Update is called once per frame 16 | public void update () { 17 | this.networkMgr.update(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Assets/Scripts/Game.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 459f24483b86a89469dd0cb841e3242b 3 | timeCreated: 1473317260 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Main.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class Main : MonoBehaviour { 5 | 6 | Game game; 7 | 8 | void Start () { 9 | GameObject go = this.gameObject; 10 | DontDestroyOnLoad(go); 11 | this.game = new Game(); 12 | this.game.init(); 13 | } 14 | 15 | void Update() { 16 | game.update(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Assets/Scripts/Main.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: d78968afef4ebf64bba684d33d1c7bf1 3 | timeCreated: 1473316883 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e7ae1a6f0d633a94a8c01d6e97de21ab 3 | folderAsset: yes 4 | timeCreated: 1473316763 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/BroadcastFact.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System; 5 | using SimpleJson; 6 | 7 | public class BroadcastFact { 8 | public static string IS_EVT_KEY_NAME = "__evt_"; 9 | public static Dictionary> callbacks = new Dictionary>(); 10 | 11 | public static void registEvents() 12 | { 13 | BroadcastFact.callbacks.Add(Routes.ON_RACE_WAIT, GameHandler.onRaceWait); 14 | } 15 | 16 | public static void invokeHandle(string route, JsonObject data) 17 | { 18 | Action handler; 19 | BroadcastFact.callbacks.TryGetValue(route, out handler); 20 | if (handler != null) 21 | { 22 | handler(data); 23 | } 24 | else 25 | { 26 | Debug.LogWarning("cannot find handler for " + route); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/BroadcastFact.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 43a0d205a24c84c47919ab1af7282208 3 | timeCreated: 1473329303 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/CallbackFact.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System; 5 | using SimpleJson; 6 | 7 | public class CallbackFact { 8 | public static string ROUTE_KEY_NAME = "__r_"; 9 | private static Dictionary> callbacks = new Dictionary>(); 10 | 11 | //注册各种 回调 12 | public static void registCallbacks() { 13 | registCallback(Routes.CONNECTOR_ENTER, ConnectorHandler.exec); 14 | } 15 | 16 | private static void registCallback(string route, Action handler) 17 | { 18 | if (CallbackFact.callbacks.ContainsKey(route)) {//已经注册过了同名的 19 | Debug.LogError("already exist route: " + route); 20 | return; 21 | } 22 | CallbackFact.callbacks.Add(route, handler); 23 | } 24 | 25 | //执行回调 26 | public static void invokeHandle(string route, JsonObject data) { 27 | Action handler; 28 | CallbackFact.callbacks.TryGetValue(route, out handler); 29 | if(handler != null) 30 | { 31 | handler(data); 32 | }else 33 | { 34 | Debug.LogWarning("cannot find handler for " + route); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/CallbackFact.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f0b477fc04b30ad49a11e88b121f3dce 3 | timeCreated: 1473322795 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/Handlers.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 978e5d3f7c9c915499b8144e7e9650cd 3 | folderAsset: yes 4 | timeCreated: 1473324240 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/Handlers/ConnectorHandler.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | using SimpleJson; 4 | 5 | public class ConnectorHandler 6 | { 7 | public static void exec(JsonObject data) 8 | { 9 | Debug.Log("ConnectorHandler.Handler"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/Handlers/ConnectorHandler.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: de94a925686b71f49975d2ca352df630 3 | timeCreated: 1473324266 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/Handlers/GameHandler.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | using SimpleJson; 4 | 5 | public class GameHandler { 6 | 7 | public static void onRaceWait(JsonObject data) { 8 | Debug.Log("onRaceWait-: " + data); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/Handlers/GameHandler.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: b43f3319a5038074e942ceaa8bc16a06 3 | timeCreated: 1473329495 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/NetworkMgr.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | using Pomelo.DotNetClient; 4 | using System; 5 | using SimpleJson; 6 | using System.Collections.Generic; 7 | 8 | public class NetworkMgr{ 9 | 10 | private string host = "127.0.0.1"; 11 | private int port = 3009; 12 | 13 | private PomeloClient pclient; 14 | private Queue msgQueue;//消息队列(收到的) 15 | 16 | private static NetworkMgr _instance; 17 | public static NetworkMgr getInstance() { 18 | if (_instance == null) { 19 | _instance = new NetworkMgr(); 20 | } 21 | return _instance; 22 | } 23 | 24 | public NetworkMgr() { 25 | this.msgQueue = new Queue(); 26 | 27 | //把回调的key和托管函数 对应起来 28 | CallbackFact.registCallbacks(); 29 | BroadcastFact.registEvents(); 30 | } 31 | 32 | //切断连接 33 | public void disconnect() { 34 | pclient.disconnect(); 35 | } 36 | 37 | //建立起一条新的连接 38 | public void newSocket() { 39 | pclient = new PomeloClient(); 40 | 41 | pclient.NetWorkStateChangedEvent += (state) => 42 | { 43 | Debug.Log(state); 44 | //Console.WriteLine(state); 45 | }; 46 | 47 | 48 | pclient.initClient(host, port, () => 49 | { 50 | //The user data is the handshake user params 51 | JsonObject user = new JsonObject(); 52 | pclient.connect(user, data => 53 | { 54 | ConnectorSender.sendEnter(); 55 | //pclient.request(Routes.CONNECTOR_ENTER, new JsonObject(), OnEnterConnector); 56 | }); 57 | 58 | //把广播事件的名称都注册到pomelo中 59 | foreach (KeyValuePair> pair in BroadcastFact.callbacks) 60 | { 61 | this.registBroadcast(pair.Key); 62 | } 63 | }); 64 | } 65 | 66 | //通知给对方服务器一个消息,不会有回传数据 67 | public void notify(string route, JsonObject message) { 68 | pclient.notify(route, message); 69 | } 70 | 71 | //请求消息,会有回调 72 | public void request(string route, JsonObject message) { 73 | pclient.request(route, message, (data) => { 74 | data[CallbackFact.ROUTE_KEY_NAME] = route; 75 | this.msgQueue.Enqueue(data); 76 | }); 77 | } 78 | 79 | //注册了 广播事件的 处理逻辑 80 | public void registBroadcast(string eventName) { 81 | pclient.on(eventName, (data) => { 82 | data[CallbackFact.ROUTE_KEY_NAME] = eventName; 83 | data[BroadcastFact.IS_EVT_KEY_NAME] = true;//表示它是一个 广播事件, 84 | this.msgQueue.Enqueue(data); 85 | }); 86 | } 87 | 88 | //扫描消息队列,看是否有数据要处理 89 | public void update() { 90 | while (this.msgQueue.Count > 0) { 91 | JsonObject data = this.msgQueue.Dequeue(); 92 | string route = data[CallbackFact.ROUTE_KEY_NAME] as string; 93 | if(route == null) 94 | { 95 | Debug.LogError("cannt find route in msg"); 96 | } 97 | //调用回调函数 98 | 99 | if (!data.ContainsKey(BroadcastFact.IS_EVT_KEY_NAME)) 100 | {//不是广播 101 | CallbackFact.invokeHandle(route, data); 102 | } 103 | else { 104 | BroadcastFact.invokeHandle(route, data); 105 | } 106 | } 107 | } 108 | 109 | 110 | } 111 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/NetworkMgr.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 960cfd23bc8e37548809b229ea2a66b6 3 | timeCreated: 1473316776 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/Routes.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class Routes { 5 | //各个路由的名称 6 | public static string CONNECTOR_ENTER = "connector.initHandler.enter"; 7 | 8 | 9 | //把事件的名称也放在这里 10 | public static string ON_RACE_WAIT = "onRaceWait"; 11 | } 12 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/Routes.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 95322d54d29d73243bf267d012f1fa38 3 | timeCreated: 1473322000 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/Senders.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: eb53505622e77404e8f61dc170ffadcd 3 | folderAsset: yes 4 | timeCreated: 1473326637 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/Senders/ConnectorSender.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | using SimpleJson; 4 | 5 | public class ConnectorSender { 6 | 7 | public static void sendEnter() { 8 | NetworkMgr.getInstance().request(Routes.CONNECTOR_ENTER, new JsonObject()); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/Senders/ConnectorSender.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 0f302c3f30b0e9c4a9a55365f682d92c 3 | timeCreated: 1473327673 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/Senders/GameSender.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class GameSender { 5 | 6 | } 7 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/Senders/GameSender.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f668917e126862e4196f16a61a619153 3 | timeCreated: 1473327684 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e2eeccdb745da554992e61bb00beb81a 3 | folderAsset: yes 4 | timeCreated: 1473317717 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/client.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: d5dda4a4b4ce4bc45ae422bb6810e5ea 3 | folderAsset: yes 4 | timeCreated: 1473317717 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/client/EventManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using SimpleJson; 5 | 6 | namespace Pomelo.DotNetClient 7 | { 8 | public class EventManager : IDisposable 9 | { 10 | private Dictionary> callBackMap; 11 | private Dictionary>> eventMap; 12 | 13 | public EventManager() 14 | { 15 | this.callBackMap = new Dictionary>(); 16 | this.eventMap = new Dictionary>>(); 17 | } 18 | 19 | //Adds callback to callBackMap by id. 20 | public void AddCallBack(uint id, Action callback) 21 | { 22 | if (id > 0 && callback != null) 23 | { 24 | this.callBackMap.Add(id, callback); 25 | } 26 | } 27 | 28 | /// 29 | /// Invoke the callback when the server return messge . 30 | /// 31 | /// 32 | /// Pomelo message. 33 | /// 34 | public void InvokeCallBack(uint id, JsonObject data) 35 | { 36 | if (!callBackMap.ContainsKey(id)) return; 37 | callBackMap[id].Invoke(data); 38 | } 39 | 40 | //Adds the event to eventMap by name. 41 | public void AddOnEvent(string eventName, Action callback) 42 | { 43 | List> list = null; 44 | if (this.eventMap.TryGetValue(eventName, out list)) 45 | { 46 | list.Add(callback); 47 | } 48 | else 49 | { 50 | list = new List>(); 51 | list.Add(callback); 52 | this.eventMap.Add(eventName, list); 53 | } 54 | } 55 | 56 | /// 57 | /// If the event exists,invoke the event when server return messge. 58 | /// 59 | /// 60 | /// 61 | /// 62 | /// 63 | public void InvokeOnEvent(string route, JsonObject msg) 64 | { 65 | if (!this.eventMap.ContainsKey(route)) return; 66 | 67 | List> list = eventMap[route]; 68 | foreach (Action action in list) action.Invoke(msg); 69 | } 70 | 71 | // Dispose() calls Dispose(true) 72 | public void Dispose() 73 | { 74 | Dispose(true); 75 | GC.SuppressFinalize(this); 76 | } 77 | 78 | // The bulk of the clean-up code is implemented in Dispose(bool) 79 | protected void Dispose(bool disposing) 80 | { 81 | this.callBackMap.Clear(); 82 | this.eventMap.Clear(); 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/client/EventManager.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 516fbdadaaff70846b25b2997389888c 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/client/PomeloClient.cs: -------------------------------------------------------------------------------- 1 | using SimpleJson; 2 | using System; 3 | using System.ComponentModel; 4 | using System.Net; 5 | using System.Net.Sockets; 6 | using System.Threading; 7 | 8 | namespace Pomelo.DotNetClient 9 | { 10 | /// 11 | /// network state enum 12 | /// 13 | public enum NetWorkState 14 | { 15 | [Description("initial state")] 16 | CLOSED, 17 | 18 | [Description("connecting server")] 19 | CONNECTING, 20 | 21 | [Description("server connected")] 22 | CONNECTED, 23 | 24 | [Description("disconnected with server")] 25 | DISCONNECTED, 26 | 27 | [Description("connect timeout")] 28 | TIMEOUT, 29 | 30 | [Description("netwrok error")] 31 | ERROR 32 | } 33 | 34 | public class PomeloClient : IDisposable 35 | { 36 | /// 37 | /// netwrok changed event 38 | /// 39 | public event Action NetWorkStateChangedEvent; 40 | 41 | 42 | private NetWorkState netWorkState = NetWorkState.CLOSED; //current network state 43 | 44 | private EventManager eventManager; 45 | private Socket socket; 46 | private Protocol protocol; 47 | private bool disposed = false; 48 | private uint reqId = 1; 49 | 50 | private ManualResetEvent timeoutEvent = new ManualResetEvent(false); 51 | private int timeoutMSec = 8000; //connect timeout count in millisecond 52 | 53 | public PomeloClient() 54 | { 55 | } 56 | 57 | //add by luo 58 | private Action _initCallback; 59 | private string _initHost; 60 | private int _initPort; 61 | 62 | private delegate void AsyncInitClient(); 63 | private AsyncInitClient _asyncDel; 64 | private void AsyncInit() 65 | { 66 | timeoutEvent.Reset(); 67 | eventManager = new EventManager(); 68 | NetWorkChanged(NetWorkState.CONNECTING); 69 | 70 | /* 71 | IPAddress ipAddress = null; 72 | 73 | try 74 | { 75 | IPAddress[] addresses = Dns.GetHostEntry(this._initHost).AddressList; 76 | foreach (var item in addresses) 77 | { 78 | if (item.AddressFamily == AddressFamily.InterNetwork) 79 | { 80 | ipAddress = item; 81 | break; 82 | } 83 | } 84 | } 85 | catch (Exception e) 86 | { 87 | NetWorkChanged(NetWorkState.ERROR); 88 | return; 89 | } 90 | 91 | if (ipAddress == null) 92 | { 93 | throw new Exception("can not parse host : " + this._initHost); 94 | } 95 | */ 96 | 97 | this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 98 | IPEndPoint ie = new IPEndPoint(IPAddress.Parse(this._initHost), this._initPort); 99 | //ipAddress 100 | 101 | socket.BeginConnect(ie, new AsyncCallback((result) => 102 | { 103 | try 104 | { 105 | this.socket.EndConnect(result); 106 | this.protocol = new Protocol(this, this.socket); 107 | NetWorkChanged(NetWorkState.CONNECTED); 108 | 109 | if (this._initCallback != null) 110 | { 111 | this._initCallback(); 112 | } 113 | } 114 | catch (SocketException e) 115 | { 116 | if (netWorkState != NetWorkState.TIMEOUT) 117 | { 118 | NetWorkChanged(NetWorkState.ERROR); 119 | } 120 | Dispose(); 121 | } 122 | finally 123 | { 124 | timeoutEvent.Set(); 125 | } 126 | }), this.socket); 127 | 128 | if (timeoutEvent.WaitOne(timeoutMSec, false)) 129 | { 130 | if (netWorkState != NetWorkState.CONNECTED && netWorkState != NetWorkState.ERROR) 131 | { 132 | NetWorkChanged(NetWorkState.TIMEOUT); 133 | Dispose(); 134 | } 135 | } 136 | } 137 | /// 138 | /// initialize pomelo client 139 | /// 140 | /// server name or server ip (www.xxx.com/127.0.0.1/::1/localhost etc.) 141 | /// server port 142 | /// socket successfully connected callback(in network thread) 143 | public void initClient(string host, int port, Action callback = null) 144 | { 145 | this._initCallback = callback;//by luo 146 | this._initHost = host; 147 | this._initPort = port; 148 | 149 | this._asyncDel = this.AsyncInit; 150 | IAsyncResult ret = this._asyncDel.BeginInvoke(null, null); 151 | 152 | 153 | 154 | } 155 | 156 | /// 157 | /// 网络状态变化 158 | /// 159 | /// 160 | private void NetWorkChanged(NetWorkState state) 161 | { 162 | netWorkState = state; 163 | 164 | if (NetWorkStateChangedEvent != null) 165 | { 166 | NetWorkStateChangedEvent(state); 167 | } 168 | } 169 | 170 | public void connect() 171 | { 172 | connect(null, null); 173 | } 174 | 175 | public void connect(JsonObject user) 176 | { 177 | connect(user, null); 178 | } 179 | 180 | public void connect(Action handshakeCallback) 181 | { 182 | connect(null, handshakeCallback); 183 | } 184 | 185 | public bool connect(JsonObject user, Action handshakeCallback) 186 | { 187 | try 188 | { 189 | protocol.start(user, handshakeCallback); 190 | return true; 191 | } 192 | catch (Exception e) 193 | { 194 | Console.WriteLine(e.ToString()); 195 | return false; 196 | } 197 | } 198 | 199 | private JsonObject emptyMsg = new JsonObject(); 200 | public void request(string route, Action action) 201 | { 202 | this.request(route, emptyMsg, action); 203 | } 204 | 205 | public void request(string route, JsonObject msg, Action action) 206 | { 207 | this.eventManager.AddCallBack(reqId, action); 208 | protocol.send(route, reqId, msg); 209 | 210 | reqId++; 211 | } 212 | 213 | public void notify(string route, JsonObject msg) 214 | { 215 | protocol.send(route, msg); 216 | } 217 | 218 | public void on(string eventName, Action action) 219 | { 220 | eventManager.AddOnEvent(eventName, action); 221 | } 222 | 223 | internal void processMessage(Message msg) 224 | { 225 | if (msg.type == MessageType.MSG_RESPONSE) 226 | { 227 | //msg.data["__route"] = msg.route; 228 | //msg.data["__type"] = "resp"; 229 | eventManager.InvokeCallBack(msg.id, msg.data); 230 | } 231 | else if (msg.type == MessageType.MSG_PUSH) 232 | { 233 | //msg.data["__route"] = msg.route; 234 | //msg.data["__type"] = "push"; 235 | eventManager.InvokeOnEvent(msg.route, msg.data); 236 | } 237 | } 238 | 239 | public void disconnect() 240 | { 241 | Dispose(); 242 | NetWorkChanged(NetWorkState.DISCONNECTED); 243 | } 244 | 245 | public void Dispose() 246 | { 247 | Dispose(true); 248 | GC.SuppressFinalize(this); 249 | } 250 | 251 | // The bulk of the clean-up code 252 | protected virtual void Dispose(bool disposing) 253 | { 254 | if (this.disposed) 255 | return; 256 | 257 | if (disposing) 258 | { 259 | // free managed resources 260 | if (this.protocol != null) 261 | { 262 | this.protocol.close(); 263 | } 264 | 265 | if (this.eventManager != null) 266 | { 267 | this.eventManager.Dispose(); 268 | } 269 | 270 | try 271 | { 272 | this.socket.Shutdown(SocketShutdown.Both); 273 | this.socket.Close(); 274 | this.socket = null; 275 | } 276 | catch (Exception) 277 | { 278 | //todo : 有待确定这里是否会出现异常,这里是参考之前官方github上pull request。emptyMsg 279 | } 280 | 281 | this.disposed = true; 282 | } 283 | } 284 | } 285 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/client/PomeloClient.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 75ffb2ebae4d45a43b323c34cb00ff59 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/client/PomeloClient.cs.old: -------------------------------------------------------------------------------- 1 | using SimpleJson; 2 | using System; 3 | using System.ComponentModel; 4 | using System.Net; 5 | using System.Net.Sockets; 6 | using System.Threading; 7 | 8 | namespace Pomelo.DotNetClient 9 | { 10 | /// 11 | /// network state enum 12 | /// 13 | public enum NetWorkState 14 | { 15 | [Description("initial state")] 16 | CLOSED, 17 | 18 | [Description("connecting server")] 19 | CONNECTING, 20 | 21 | [Description("server connected")] 22 | CONNECTED, 23 | 24 | [Description("disconnected with server")] 25 | DISCONNECTED, 26 | 27 | [Description("connect timeout")] 28 | TIMEOUT, 29 | 30 | [Description("netwrok error")] 31 | ERROR 32 | } 33 | 34 | public class PomeloClient : IDisposable 35 | { 36 | /// 37 | /// netwrok changed event 38 | /// 39 | public event Action NetWorkStateChangedEvent; 40 | 41 | 42 | private NetWorkState netWorkState = NetWorkState.CLOSED; //current network state 43 | 44 | private EventManager eventManager; 45 | private Socket socket; 46 | private Protocol protocol; 47 | private bool disposed = false; 48 | private uint reqId = 1; 49 | 50 | private ManualResetEvent timeoutEvent = new ManualResetEvent(false); 51 | private int timeoutMSec = 8000; //connect timeout count in millisecond 52 | 53 | public PomeloClient() 54 | { 55 | } 56 | 57 | /// 58 | /// initialize pomelo client 59 | /// 60 | /// server name or server ip (www.xxx.com/127.0.0.1/::1/localhost etc.) 61 | /// server port 62 | /// socket successfully connected callback(in network thread) 63 | public void initClient(string host, int port, Action callback = null) 64 | { 65 | timeoutEvent.Reset(); 66 | eventManager = new EventManager(); 67 | NetWorkChanged(NetWorkState.CONNECTING); 68 | 69 | IPAddress ipAddress = null; 70 | 71 | try 72 | { 73 | IPAddress[] addresses = Dns.GetHostEntry(host).AddressList; 74 | foreach (var item in addresses) 75 | { 76 | if (item.AddressFamily == AddressFamily.InterNetwork) 77 | { 78 | ipAddress = item; 79 | break; 80 | } 81 | } 82 | } 83 | catch (Exception e) 84 | { 85 | NetWorkChanged(NetWorkState.ERROR); 86 | return; 87 | } 88 | 89 | if (ipAddress == null) 90 | { 91 | throw new Exception("can not parse host : " + host); 92 | } 93 | 94 | this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 95 | IPEndPoint ie = new IPEndPoint(ipAddress, port); 96 | 97 | socket.BeginConnect(ie, new AsyncCallback((result) => 98 | { 99 | try 100 | { 101 | this.socket.EndConnect(result); 102 | this.protocol = new Protocol(this, this.socket); 103 | NetWorkChanged(NetWorkState.CONNECTED); 104 | 105 | if (callback != null) 106 | { 107 | callback(); 108 | } 109 | } 110 | catch (SocketException e) 111 | { 112 | if (netWorkState != NetWorkState.TIMEOUT) 113 | { 114 | NetWorkChanged(NetWorkState.ERROR); 115 | } 116 | Dispose(); 117 | } 118 | finally 119 | { 120 | timeoutEvent.Set(); 121 | } 122 | }), this.socket); 123 | 124 | if (timeoutEvent.WaitOne(timeoutMSec, false)) 125 | { 126 | if (netWorkState != NetWorkState.CONNECTED && netWorkState != NetWorkState.ERROR) 127 | { 128 | NetWorkChanged(NetWorkState.TIMEOUT); 129 | Dispose(); 130 | } 131 | } 132 | } 133 | 134 | /// 135 | /// 网络状态变化 136 | /// 137 | /// 138 | private void NetWorkChanged(NetWorkState state) 139 | { 140 | netWorkState = state; 141 | 142 | if (NetWorkStateChangedEvent != null) 143 | { 144 | NetWorkStateChangedEvent(state); 145 | } 146 | } 147 | 148 | public void connect() 149 | { 150 | connect(null, null); 151 | } 152 | 153 | public void connect(JsonObject user) 154 | { 155 | connect(user, null); 156 | } 157 | 158 | public void connect(Action handshakeCallback) 159 | { 160 | connect(null, handshakeCallback); 161 | } 162 | 163 | public bool connect(JsonObject user, Action handshakeCallback) 164 | { 165 | try 166 | { 167 | protocol.start(user, handshakeCallback); 168 | return true; 169 | } 170 | catch (Exception e) 171 | { 172 | Console.WriteLine(e.ToString()); 173 | return false; 174 | } 175 | } 176 | 177 | private JsonObject emptyMsg = new JsonObject(); 178 | public void request(string route, Action action) 179 | { 180 | this.request(route, emptyMsg, action); 181 | } 182 | 183 | public void request(string route, JsonObject msg, Action action) 184 | { 185 | this.eventManager.AddCallBack(reqId, action); 186 | protocol.send(route, reqId, msg); 187 | 188 | reqId++; 189 | } 190 | 191 | public void notify(string route, JsonObject msg) 192 | { 193 | protocol.send(route, msg); 194 | } 195 | 196 | public void on(string eventName, Action action) 197 | { 198 | eventManager.AddOnEvent(eventName, action); 199 | } 200 | 201 | internal void processMessage(Message msg) 202 | { 203 | if (msg.type == MessageType.MSG_RESPONSE) 204 | { 205 | //msg.data["__route"] = msg.route; 206 | //msg.data["__type"] = "resp"; 207 | eventManager.InvokeCallBack(msg.id, msg.data); 208 | } 209 | else if (msg.type == MessageType.MSG_PUSH) 210 | { 211 | //msg.data["__route"] = msg.route; 212 | //msg.data["__type"] = "push"; 213 | eventManager.InvokeOnEvent(msg.route, msg.data); 214 | } 215 | } 216 | 217 | public void disconnect() 218 | { 219 | Dispose(); 220 | NetWorkChanged(NetWorkState.DISCONNECTED); 221 | } 222 | 223 | public void Dispose() 224 | { 225 | Dispose(true); 226 | GC.SuppressFinalize(this); 227 | } 228 | 229 | // The bulk of the clean-up code 230 | protected virtual void Dispose(bool disposing) 231 | { 232 | if (this.disposed) 233 | return; 234 | 235 | if (disposing) 236 | { 237 | // free managed resources 238 | if (this.protocol != null) 239 | { 240 | this.protocol.close(); 241 | } 242 | 243 | if (this.eventManager != null) 244 | { 245 | this.eventManager.Dispose(); 246 | } 247 | 248 | try 249 | { 250 | this.socket.Shutdown(SocketShutdown.Both); 251 | this.socket.Close(); 252 | this.socket = null; 253 | } 254 | catch (Exception) 255 | { 256 | //todo : 有待确定这里是否会出现异常,这里是参考之前官方github上pull request。emptyMsg 257 | } 258 | 259 | this.disposed = true; 260 | } 261 | } 262 | } 263 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/client/PomeloClient.cs.old.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 12ec0a3f26b42cb45aabd4b448793444 3 | timeCreated: 1473320223 4 | licenseType: Pro 5 | DefaultImporter: 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/client/test.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 853a1517c8182854ca894fc2ce5c8c0b 3 | folderAsset: yes 4 | timeCreated: 1473317717 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/client/test/ClientTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using SimpleJson; 3 | 4 | namespace Pomelo.DotNetClient.Test 5 | { 6 | public class ClientTest 7 | { 8 | public static PomeloClient pc = null; 9 | 10 | public static void loginTest(string host, int port) 11 | { 12 | pc = new PomeloClient(); 13 | 14 | pc.NetWorkStateChangedEvent += (state) => 15 | { 16 | Console.WriteLine(state); 17 | }; 18 | 19 | 20 | pc.initClient(host, port, () => 21 | { 22 | pc.connect(null, data => 23 | { 24 | 25 | Console.WriteLine("on data back" + data.ToString()); 26 | JsonObject msg = new JsonObject(); 27 | msg["uid"] = 111; 28 | pc.request("gate.gateHandler.queryEntry", msg, OnQuery); 29 | }); 30 | }); 31 | } 32 | 33 | public static void OnQuery(JsonObject result) 34 | { 35 | if (Convert.ToInt32(result["code"]) == 200) 36 | { 37 | pc.disconnect(); 38 | 39 | string host = (string)result["host"]; 40 | int port = Convert.ToInt32(result["port"]); 41 | pc = new PomeloClient(); 42 | 43 | pc.NetWorkStateChangedEvent += (state) => 44 | { 45 | Console.WriteLine(state); 46 | }; 47 | 48 | pc.initClient(host, port, () => 49 | { 50 | pc.connect(null, (data) => 51 | { 52 | JsonObject userMessage = new JsonObject(); 53 | Console.WriteLine("on connect to connector!"); 54 | 55 | //Login 56 | JsonObject msg = new JsonObject(); 57 | msg["username"] = "test"; 58 | msg["rid"] = "pomelo"; 59 | 60 | pc.request("connector.entryHandler.enter", msg, OnEnter); 61 | }); 62 | }); 63 | } 64 | } 65 | 66 | public static void OnEnter(JsonObject result) 67 | { 68 | Console.WriteLine("on login " + result.ToString()); 69 | } 70 | 71 | public static void onDisconnect(JsonObject result) 72 | { 73 | Console.WriteLine("on sockect disconnected!"); 74 | } 75 | 76 | public static void Run() 77 | { 78 | string host = "192.168.0.156"; 79 | int port = 3014; 80 | 81 | loginTest(host, port); 82 | } 83 | } 84 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/client/test/ClientTest.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 618d4bb938625d14ca5ef9235de5418a 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/lib.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 60840c162c739e8409cfb974a9a046e3 3 | folderAsset: yes 4 | timeCreated: 1473317767 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/lib/SimpleJson.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/Assets/Scripts/Networks/pomelo/lib/SimpleJson.dll -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/lib/SimpleJson.dll.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 5e68ae3d8b79fef4f879977c26098aba 3 | timeCreated: 1473317768 4 | licenseType: Pro 5 | PluginImporter: 6 | serializedVersion: 1 7 | iconMap: {} 8 | executionOrder: {} 9 | isPreloaded: 0 10 | platformData: 11 | Any: 12 | enabled: 1 13 | settings: {} 14 | Editor: 15 | enabled: 0 16 | settings: 17 | DefaultValueInitialized: true 18 | WindowsStoreApps: 19 | enabled: 0 20 | settings: 21 | CPU: AnyCPU 22 | userData: 23 | assetBundleName: 24 | assetBundleVariant: 25 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 889722f1ff411314cba9af309cd7ddbb 3 | folderAsset: yes 4 | timeCreated: 1473317717 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/Decoder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Pomelo.Protobuf 4 | { 5 | public class Decoder 6 | { 7 | /// 8 | /// Decodes the UInt32. 9 | /// 10 | public static uint decodeUInt32(int offset, byte[] bytes, out int length) 11 | { 12 | uint n = 0; 13 | length = 0; 14 | 15 | for (int i = offset; i < bytes.Length; i++) 16 | { 17 | length++; 18 | uint m = Convert.ToUInt32(bytes[i]); 19 | n = n + Convert.ToUInt32((m & 0x7f) * Math.Pow(2, (7 * (i - offset)))); 20 | if (m < 128) 21 | { 22 | break; 23 | } 24 | } 25 | 26 | return n; 27 | } 28 | 29 | public static uint decodeUInt32(byte[] bytes) 30 | { 31 | int length; 32 | return decodeUInt32(0, bytes, out length); 33 | } 34 | 35 | /// 36 | /// Decodes the SInt32. 37 | /// 38 | public static int decodeSInt32(byte[] bytes) 39 | { 40 | uint n = decodeUInt32(bytes); 41 | int flag = ((n % 2) == 1) ? -1 : 1; 42 | 43 | int result = Convert.ToInt32(((n % 2 + n) / 2) * flag); 44 | return result; 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/Decoder.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: eb05093765548f64aa11898568322528 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/Encoder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | 5 | namespace Pomelo.Protobuf 6 | { 7 | public class Encoder 8 | { 9 | 10 | //Encode the UInt32. 11 | public static byte[] encodeUInt32(string n) 12 | { 13 | return encodeUInt32(Convert.ToUInt32(n)); 14 | } 15 | 16 | /// 17 | /// Encode the UInt32. 18 | /// 19 | /// 20 | /// byte[] 21 | /// 22 | /// 23 | /// int 24 | /// 25 | public static byte[] encodeUInt32(uint n) 26 | { 27 | List byteList = new List(); 28 | do 29 | { 30 | uint tmp = n % 128; 31 | uint next = n >> 7; 32 | if (next != 0) 33 | { 34 | tmp = tmp + 128; 35 | } 36 | byteList.Add(Convert.ToByte(tmp)); 37 | n = next; 38 | } while (n != 0); 39 | 40 | return byteList.ToArray(); 41 | } 42 | 43 | //Encode SInt32 44 | public static byte[] encodeSInt32(string n) 45 | { 46 | return encodeSInt32(Convert.ToInt32(n)); 47 | } 48 | 49 | /// 50 | /// Encodes the SInt32. 51 | /// 52 | /// 53 | /// byte [] 54 | /// 55 | /// 56 | /// int 57 | /// 58 | public static byte[] encodeSInt32(int n) 59 | { 60 | UInt32 num = (uint)(n < 0 ? (Math.Abs(n) * 2 - 1) : n * 2); 61 | return encodeUInt32(num); 62 | } 63 | 64 | /// 65 | /// Encodes the float. 66 | /// 67 | /// 68 | /// byte [] 69 | /// 70 | /// 71 | /// float. 72 | /// 73 | public static byte[] encodeFloat(float n) 74 | { 75 | byte[] bytes = BitConverter.GetBytes(n); 76 | if (!BitConverter.IsLittleEndian) 77 | { 78 | Util.Reverse(bytes); 79 | } 80 | return bytes; 81 | } 82 | 83 | //Get the byte length of message. 84 | public static int byteLength(string msg) 85 | { 86 | return System.Text.Encoding.UTF8.GetBytes(msg).Length; 87 | } 88 | 89 | 90 | } 91 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/Encoder.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: b1c5a58e3afaea44bb0bc527f45b5951 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/MsgDecoder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using SimpleJson; 4 | using System.Collections; 5 | using System.Collections.Generic; 6 | 7 | namespace Pomelo.Protobuf 8 | { 9 | public class MsgDecoder 10 | { 11 | private JsonObject protos { set; get; }//The message format(like .proto file) 12 | private int offset { set; get; } 13 | private byte[] buffer { set; get; }//The binary message from server. 14 | private Util util { set; get; } 15 | 16 | public MsgDecoder(JsonObject protos) 17 | { 18 | if (protos == null) protos = new JsonObject(); 19 | 20 | this.protos = protos; 21 | this.util = new Util(); 22 | } 23 | 24 | /// 25 | /// Decode message from server. 26 | /// 27 | /// 28 | /// Route. 29 | /// 30 | /// 31 | /// JsonObject. 32 | /// 33 | public JsonObject decode(string route, byte[] buf) 34 | { 35 | this.buffer = buf; 36 | this.offset = 0; 37 | object proto = null; 38 | if (this.protos.TryGetValue(route, out proto)) 39 | { 40 | JsonObject msg = new JsonObject(); 41 | return this.decodeMsg(msg, (JsonObject)proto, this.buffer.Length); 42 | } 43 | return null; 44 | } 45 | 46 | 47 | /// 48 | /// Decode the message. 49 | /// 50 | /// 51 | /// The message. 52 | /// 53 | /// 54 | /// JsonObject. 55 | /// 56 | /// 57 | /// JsonObject. 58 | /// 59 | /// 60 | /// int. 61 | /// 62 | private JsonObject decodeMsg(JsonObject msg, JsonObject proto, int length) 63 | { 64 | while (this.offset < length) 65 | { 66 | Dictionary head = this.getHead(); 67 | int tag; 68 | if (head.TryGetValue("tag", out tag)) 69 | { 70 | object _tags = null; 71 | if (proto.TryGetValue("__tags", out _tags)) 72 | { 73 | object name; 74 | if (((JsonObject)_tags).TryGetValue(tag.ToString(), out name)) 75 | { 76 | object value; 77 | if (proto.TryGetValue(name.ToString(), out value)) 78 | { 79 | object option; 80 | if (((JsonObject)(value)).TryGetValue("option", out option)) 81 | { 82 | switch (option.ToString()) 83 | { 84 | case "optional": 85 | case "required": 86 | object type; 87 | if (((JsonObject)(value)).TryGetValue("type", out type)) 88 | { 89 | msg.Add(name.ToString(), this.decodeProp(type.ToString(), proto)); 90 | } 91 | break; 92 | case "repeated": 93 | object _name; 94 | if (!msg.TryGetValue(name.ToString(), out _name)) 95 | { 96 | msg.Add(name.ToString(), new List()); 97 | } 98 | object value_type; 99 | if (msg.TryGetValue(name.ToString(), out _name) && ((JsonObject)(value)).TryGetValue("type", out value_type)) 100 | { 101 | decodeArray((List)_name, value_type.ToString(), proto); 102 | } 103 | break; 104 | } 105 | } 106 | } 107 | } 108 | } 109 | } 110 | } 111 | return msg; 112 | } 113 | 114 | /// 115 | /// Decode array in message. 116 | /// 117 | private void decodeArray(List list, string type, JsonObject proto) 118 | { 119 | if (this.util.isSimpleType(type)) 120 | { 121 | int length = (int)Decoder.decodeUInt32(this.getBytes()); 122 | for (int i = 0; i < length; i++) 123 | { 124 | list.Add(this.decodeProp(type, null)); 125 | } 126 | } 127 | else 128 | { 129 | list.Add(this.decodeProp(type, proto)); 130 | } 131 | } 132 | 133 | /// 134 | /// Decode each simple type in message. 135 | /// 136 | private object decodeProp(string type, JsonObject proto) 137 | { 138 | switch (type) 139 | { 140 | case "uInt32": 141 | return Decoder.decodeUInt32(this.getBytes()); 142 | case "int32": 143 | case "sInt32": 144 | return Decoder.decodeSInt32(this.getBytes()); 145 | case "float": 146 | return this.decodeFloat(); 147 | case "double": 148 | return this.decodeDouble(); 149 | case "string": 150 | return this.decodeString(); 151 | default: 152 | return this.decodeObject(type, proto); 153 | } 154 | } 155 | 156 | //Decode the user-defined object type in message. 157 | private JsonObject decodeObject(string type, JsonObject proto) 158 | { 159 | if (proto != null) 160 | { 161 | object __messages; 162 | if (proto.TryGetValue("__messages", out __messages)) 163 | { 164 | object _type; 165 | if (((JsonObject)__messages).TryGetValue(type, out _type) || protos.TryGetValue("message " + type, out _type)) 166 | { 167 | int l = (int)Decoder.decodeUInt32(this.getBytes()); 168 | JsonObject msg = new JsonObject(); 169 | return this.decodeMsg(msg, (JsonObject)_type, this.offset + l); 170 | } 171 | } 172 | } 173 | return new JsonObject(); 174 | } 175 | 176 | //Decode string type. 177 | private string decodeString() 178 | { 179 | int length = (int)Decoder.decodeUInt32(this.getBytes()); 180 | string msg_string = Encoding.UTF8.GetString(this.buffer, this.offset, length); 181 | this.offset += length; 182 | return msg_string; 183 | } 184 | 185 | //Decode double type. 186 | private double decodeDouble() 187 | { 188 | double msg_double = BitConverter.Int64BitsToDouble((long)this.ReadRawLittleEndian64()); 189 | this.offset += 8; 190 | return msg_double; 191 | } 192 | 193 | //Decode float type 194 | private float decodeFloat() 195 | { 196 | float msg_float = BitConverter.ToSingle(this.buffer, this.offset); 197 | this.offset += 4; 198 | return msg_float; 199 | } 200 | 201 | //Read long in littleEndian 202 | private ulong ReadRawLittleEndian64() 203 | { 204 | ulong b1 = buffer[this.offset]; 205 | ulong b2 = buffer[this.offset + 1]; 206 | ulong b3 = buffer[this.offset + 2]; 207 | ulong b4 = buffer[this.offset + 3]; 208 | ulong b5 = buffer[this.offset + 4]; 209 | ulong b6 = buffer[this.offset + 5]; 210 | ulong b7 = buffer[this.offset + 6]; 211 | ulong b8 = buffer[this.offset + 7]; 212 | return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24) 213 | | (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56); 214 | } 215 | 216 | //Get the type and tag. 217 | private Dictionary getHead() 218 | { 219 | int tag = (int)Decoder.decodeUInt32(this.getBytes()); 220 | Dictionary head = new Dictionary(); 221 | head.Add("type", tag & 0x7); 222 | head.Add("tag", tag >> 3); 223 | return head; 224 | } 225 | 226 | //Get bytes. 227 | private byte[] getBytes() 228 | { 229 | List arrayList = new List(); 230 | int pos = this.offset; 231 | byte b; 232 | do 233 | { 234 | b = this.buffer[pos]; 235 | arrayList.Add(b); 236 | pos++; 237 | } while (b >= 128); 238 | this.offset = pos; 239 | int length = arrayList.Count; 240 | byte[] bytes = new byte[length]; 241 | for (int i = 0; i < length; i++) 242 | { 243 | bytes[i] = arrayList[i]; 244 | } 245 | return bytes; 246 | } 247 | } 248 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/MsgDecoder.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 52a86d44e5315ce4da08e7ee0dacfa4e 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/MsgEncoder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using SimpleJson; 4 | using System.Collections; 5 | using System.Collections.Generic; 6 | 7 | namespace Pomelo.Protobuf 8 | { 9 | public class MsgEncoder 10 | { 11 | private JsonObject protos { set; get; }//The message format(like .proto file) 12 | private Encoder encoder { set; get; } 13 | private Util util { set; get; } 14 | 15 | public MsgEncoder(JsonObject protos) 16 | { 17 | if (protos == null) protos = new JsonObject(); 18 | 19 | this.protos = protos; 20 | this.util = new Util(); 21 | } 22 | 23 | /// 24 | /// Encode the message from server. 25 | /// 26 | /// 27 | /// Route. 28 | /// 29 | /// 30 | /// Message. 31 | /// 32 | public byte[] encode(string route, JsonObject msg) 33 | { 34 | byte[] returnByte = null; 35 | object proto; 36 | if (this.protos.TryGetValue(route, out proto)) 37 | { 38 | if (!checkMsg(msg, (JsonObject)proto)) 39 | { 40 | return null; 41 | } 42 | int length = Encoder.byteLength(msg.ToString()) * 2; 43 | int offset = 0; 44 | byte[] buff = new byte[length]; 45 | offset = encodeMsg(buff, offset, (JsonObject)proto, msg); 46 | returnByte = new byte[offset]; 47 | for (int i = 0; i < offset; i++) 48 | { 49 | returnByte[i] = buff[i]; 50 | } 51 | } 52 | return returnByte; 53 | } 54 | 55 | /// 56 | /// Check the message. 57 | /// 58 | private bool checkMsg(JsonObject msg, JsonObject proto) 59 | { 60 | ICollection protoKeys = proto.Keys; 61 | foreach (string key in protoKeys) 62 | { 63 | JsonObject value = (JsonObject)proto[key]; 64 | object proto_option; 65 | if (value.TryGetValue("option", out proto_option)) 66 | { 67 | switch (proto_option.ToString()) 68 | { 69 | case "required": 70 | if (!msg.ContainsKey(key)) 71 | { 72 | return false; 73 | } 74 | else 75 | { 76 | 77 | } 78 | break; 79 | case "optional": 80 | object value_type; 81 | 82 | JsonObject messages = (JsonObject)proto["__messages"]; 83 | 84 | value_type = value["type"]; 85 | 86 | if (msg.ContainsKey(key)) 87 | { 88 | Object value_proto; 89 | 90 | if (messages.TryGetValue(value_type.ToString(), out value_proto) || protos.TryGetValue("message " + value_type.ToString(), out value_proto)) 91 | { 92 | checkMsg((JsonObject)msg[key], (JsonObject)value_proto); 93 | } 94 | } 95 | break; 96 | case "repeated": 97 | object msg_name; 98 | object msg_type; 99 | if (value.TryGetValue("type", out value_type) && msg.TryGetValue(key, out msg_name)) 100 | { 101 | if (((JsonObject)proto["__messages"]).TryGetValue(value_type.ToString(), out msg_type) || protos.TryGetValue("message " + value_type.ToString(), out msg_type)) 102 | { 103 | List o = (List)msg_name; 104 | foreach (object item in o) 105 | { 106 | if (!checkMsg((JsonObject)item, (JsonObject)msg_type)) 107 | { 108 | return false; 109 | } 110 | } 111 | } 112 | } 113 | break; 114 | } 115 | } 116 | } 117 | return true; 118 | } 119 | 120 | /// 121 | /// Encode the message. 122 | /// 123 | private int encodeMsg(byte[] buffer, int offset, JsonObject proto, JsonObject msg) 124 | { 125 | ICollection msgKeys = msg.Keys; 126 | foreach (string key in msgKeys) 127 | { 128 | object value; 129 | if (proto.TryGetValue(key, out value)) 130 | { 131 | object value_option; 132 | if (((JsonObject)value).TryGetValue("option", out value_option)) 133 | { 134 | switch (value_option.ToString()) 135 | { 136 | case "required": 137 | case "optional": 138 | object value_type, value_tag; 139 | if (((JsonObject)value).TryGetValue("type", out value_type) && ((JsonObject)value).TryGetValue("tag", out value_tag)) 140 | { 141 | offset = this.writeBytes(buffer, offset, this.encodeTag(value_type.ToString(), Convert.ToInt32(value_tag))); 142 | offset = this.encodeProp(msg[key], value_type.ToString(), offset, buffer, proto); 143 | } 144 | break; 145 | case "repeated": 146 | object msg_key; 147 | if (msg.TryGetValue(key, out msg_key)) 148 | { 149 | if (((List)msg_key).Count > 0) 150 | { 151 | offset = encodeArray((List)msg_key, (JsonObject)value, offset, buffer, proto); 152 | } 153 | } 154 | break; 155 | } 156 | } 157 | 158 | } 159 | } 160 | return offset; 161 | } 162 | 163 | /// 164 | /// Encode the array type. 165 | /// 166 | private int encodeArray(List msg, JsonObject value, int offset, byte[] buffer, JsonObject proto) 167 | { 168 | object value_type, value_tag; 169 | if (value.TryGetValue("type", out value_type) && value.TryGetValue("tag", out value_tag)) 170 | { 171 | if (this.util.isSimpleType(value_type.ToString())) 172 | { 173 | offset = this.writeBytes(buffer, offset, this.encodeTag(value_type.ToString(), Convert.ToInt32(value_tag))); 174 | offset = this.writeBytes(buffer, offset, Encoder.encodeUInt32((uint)msg.Count)); 175 | foreach (object item in msg) 176 | { 177 | offset = this.encodeProp(item, value_type.ToString(), offset, buffer, null); 178 | } 179 | } 180 | else 181 | { 182 | foreach (object item in msg) 183 | { 184 | offset = this.writeBytes(buffer, offset, this.encodeTag(value_type.ToString(), Convert.ToInt32(value_tag))); 185 | offset = this.encodeProp(item, value_type.ToString(), offset, buffer, proto); 186 | } 187 | } 188 | } 189 | return offset; 190 | } 191 | 192 | /// 193 | /// Encode each item in message. 194 | /// 195 | private int encodeProp(object value, string type, int offset, byte[] buffer, JsonObject proto) 196 | { 197 | switch (type) 198 | { 199 | case "uInt32": 200 | this.writeUInt32(buffer, ref offset, value); 201 | break; 202 | case "int32": 203 | case "sInt32": 204 | this.writeInt32(buffer, ref offset, value); 205 | break; 206 | case "float": 207 | this.writeFloat(buffer, ref offset, value); 208 | break; 209 | case "double": 210 | this.writeDouble(buffer, ref offset, value); 211 | break; 212 | case "string": 213 | this.writeString(buffer, ref offset, value); 214 | break; 215 | default: 216 | object __messages; 217 | object __message_type; 218 | 219 | if (proto.TryGetValue("__messages", out __messages)) 220 | { 221 | if (((JsonObject)__messages).TryGetValue(type, out __message_type) || protos.TryGetValue("message " + type, out __message_type)) 222 | { 223 | byte[] tembuff = new byte[Encoder.byteLength(value.ToString()) * 3]; 224 | int length = 0; 225 | length = this.encodeMsg(tembuff, length, (JsonObject)__message_type, (JsonObject)value); 226 | offset = writeBytes(buffer, offset, Encoder.encodeUInt32((uint)length)); 227 | for (int i = 0; i < length; i++) 228 | { 229 | buffer[offset] = tembuff[i]; 230 | offset++; 231 | } 232 | } 233 | } 234 | break; 235 | } 236 | return offset; 237 | } 238 | 239 | //Encode string. 240 | private void writeString(byte[] buffer, ref int offset, object value) 241 | { 242 | int le = Encoding.UTF8.GetByteCount(value.ToString()); 243 | offset = writeBytes(buffer, offset, Encoder.encodeUInt32((uint)le)); 244 | byte[] bytes = Encoding.UTF8.GetBytes(value.ToString()); 245 | this.writeBytes(buffer, offset, bytes); 246 | offset += le; 247 | } 248 | 249 | //Encode double. 250 | private void writeDouble(byte[] buffer, ref int offset, object value) 251 | { 252 | WriteRawLittleEndian64(buffer, offset, (ulong)BitConverter.DoubleToInt64Bits(double.Parse(value.ToString()))); 253 | offset += 8; 254 | } 255 | 256 | //Encode float. 257 | private void writeFloat(byte[] buffer, ref int offset, object value) 258 | { 259 | this.writeBytes(buffer, offset, Encoder.encodeFloat(float.Parse(value.ToString()))); 260 | offset += 4; 261 | } 262 | 263 | ////Encode UInt32. 264 | private void writeUInt32(byte[] buffer, ref int offset, object value) 265 | { 266 | offset = writeBytes(buffer, offset, Encoder.encodeUInt32(value.ToString())); 267 | } 268 | 269 | //Encode Int32 270 | private void writeInt32(byte[] buffer, ref int offset, object value) 271 | { 272 | offset = writeBytes(buffer, offset, Encoder.encodeSInt32(value.ToString())); 273 | } 274 | 275 | //Write bytes to buffer. 276 | private int writeBytes(byte[] buffer, int offset, byte[] bytes) 277 | { 278 | for (int i = 0; i < bytes.Length; i++) 279 | { 280 | buffer[offset] = bytes[i]; 281 | offset++; 282 | } 283 | return offset; 284 | } 285 | 286 | //Encode tag. 287 | private byte[] encodeTag(string type, int tag) 288 | { 289 | int flag = this.util.containType(type); 290 | return Encoder.encodeUInt32((uint)(tag << 3 | flag)); 291 | } 292 | 293 | 294 | private void WriteRawLittleEndian64(byte[] buffer, int offset, ulong value) 295 | { 296 | buffer[offset++] = ((byte)value); 297 | buffer[offset++] = ((byte)(value >> 8)); 298 | buffer[offset++] = ((byte)(value >> 16)); 299 | buffer[offset++] = ((byte)(value >> 24)); 300 | buffer[offset++] = ((byte)(value >> 32)); 301 | buffer[offset++] = ((byte)(value >> 40)); 302 | buffer[offset++] = ((byte)(value >> 48)); 303 | buffer[offset++] = ((byte)(value >> 56)); 304 | } 305 | } 306 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/MsgEncoder.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: b36875fc44ffa954e9e58f95a63e1dcc 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/Protobuf.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using SimpleJson; 3 | 4 | namespace Pomelo.Protobuf 5 | { 6 | public class Protobuf 7 | { 8 | private MsgDecoder decoder; 9 | private MsgEncoder encoder; 10 | 11 | public Protobuf(JsonObject encodeProtos, JsonObject decodeProtos) 12 | { 13 | this.encoder = new MsgEncoder(encodeProtos); 14 | this.decoder = new MsgDecoder(decodeProtos); 15 | } 16 | 17 | public byte[] encode(string route, JsonObject msg) 18 | { 19 | return encoder.encode(route, msg); 20 | } 21 | 22 | public JsonObject decode(string route, byte[] buffer) 23 | { 24 | return decoder.decode(route, buffer); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/Protobuf.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 5a0c4457adc71964e84fed4de99d7224 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/test.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: af51cc624bae8464192d07ece74b1863 3 | folderAsset: yes 4 | timeCreated: 1473317717 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/test/CodecTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using Pomelo.Protobuf; 4 | 5 | namespace Pomelo.Protobuf.Test 6 | { 7 | public class CodecTest 8 | { 9 | public static bool EncodeSInt32Test(int count) 10 | { 11 | Random random = new Random(); 12 | 13 | int flag = -1; 14 | for (int i = 0; i < count; i++) 15 | { 16 | flag *= -1; 17 | int num = random.Next(0, 0x7fffffff) * flag; 18 | byte[] bytes = Encoder.encodeSInt32(num); 19 | int result = Decoder.decodeSInt32(bytes); 20 | if (num != result) return false; 21 | } 22 | 23 | return true; 24 | } 25 | 26 | public static bool EncodeUInt32Test(int count) 27 | { 28 | Random random = new Random(); 29 | for (int i = 0; i < count; i++) 30 | { 31 | uint num = (uint)random.Next(0, 0x7fffffff); 32 | byte[] bytes = Encoder.encodeUInt32(num); 33 | uint result = Decoder.decodeUInt32(bytes); 34 | if (num != result) return false; 35 | } 36 | 37 | return true; 38 | } 39 | 40 | public static bool Run() 41 | { 42 | bool success = true, flag = false; 43 | DateTime start, end; 44 | 45 | start = DateTime.Now; 46 | flag = EncodeSInt32Test(10000); 47 | end = DateTime.Now; 48 | Console.WriteLine("Encode sint32 test finished , result is : {1}, cost time : {0}", end - start, flag); 49 | if (!flag) success = false; 50 | 51 | start = DateTime.Now; 52 | flag = EncodeUInt32Test(10000); 53 | end = DateTime.Now; 54 | Console.WriteLine("Encode uint32 test finished , result is : {1}, cost time : {0}", end - start, flag); 55 | if (!flag) success = false; 56 | 57 | return success; 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/test/CodecTest.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 299a27f362d6fa6429255a6765aef805 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/test/ProtobufTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using SimpleJson; 5 | using Pomelo.Protobuf; 6 | 7 | namespace Pomelo.Protobuf.Test 8 | { 9 | public class ProtobufTest 10 | { 11 | public static JsonObject read(string name) 12 | { 13 | StreamReader file = new StreamReader(name); 14 | 15 | String str = file.ReadToEnd(); 16 | 17 | return (JsonObject)SimpleJson.SimpleJson.DeserializeObject(str); 18 | } 19 | 20 | public static bool equal(JsonObject a, JsonObject b) 21 | { 22 | ICollection keys0 = a.Keys; 23 | ICollection keys1 = b.Keys; 24 | 25 | foreach (string key in keys0) 26 | { 27 | Console.WriteLine(a[key].GetType()); 28 | if (a[key].GetType().ToString() == "SimpleJson.JsonObject") 29 | { 30 | if (!equal((JsonObject)a[key], (JsonObject)b[key])) return false; 31 | } 32 | else if (a[key].GetType().ToString() == "SimpleJson.JsonArray") 33 | { 34 | continue; 35 | } 36 | else 37 | { 38 | if (!a[key].ToString().Equals(b[key].ToString())) return false; 39 | } 40 | } 41 | 42 | return true; 43 | } 44 | 45 | public static void Run() 46 | { 47 | JsonObject protos = read("../../json/rootProtos.json"); 48 | JsonObject msgs = read("../../json/rootMsg.json"); 49 | 50 | Protobuf protobuf = new Protobuf(protos, protos); 51 | 52 | ICollection keys = msgs.Keys; 53 | 54 | foreach (string key in keys) 55 | { 56 | JsonObject msg = (JsonObject)msgs[key]; 57 | byte[] bytes = protobuf.encode(key, msg); 58 | JsonObject result = protobuf.decode(key, bytes); 59 | if (!equal(msg, result)) 60 | { 61 | Console.WriteLine("protobuf test failed!"); 62 | return; 63 | } 64 | } 65 | 66 | Console.WriteLine("Protobuf test success!"); 67 | } 68 | 69 | private static void print(byte[] bytes, int offset, int length) 70 | { 71 | for (int i = offset; i < length; i++) 72 | Console.Write(Convert.ToString(bytes[i], 16) + " "); 73 | Console.WriteLine(); 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/test/ProtobufTest.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 909cf2cc906d2cf47b452790172488fd 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/util.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 1335f585da6df3049a2274bc130270c6 3 | folderAsset: yes 4 | timeCreated: 1473317717 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/util/Util.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | 5 | namespace Pomelo.Protobuf 6 | { 7 | public class Util 8 | { 9 | //Simple type 10 | private string[] types; 11 | private Dictionary typeMap; 12 | 13 | public Util() 14 | { 15 | this.initTypeMap(); 16 | this.types = new string[] { "uInt32", "sInt32", "int32", "uInt64", "sInt64", "float", "double" }; 17 | } 18 | 19 | /// 20 | /// Check out the given type. If it is simple, return ture. 21 | /// 22 | /// 23 | /// The simple type. 24 | /// 25 | /// 26 | /// If set to true type. 27 | /// 28 | public bool isSimpleType(string type) 29 | { 30 | int length = types.Length; 31 | bool flag = false; 32 | for (int i = 0; i < length; i++) 33 | { 34 | if (type == types[i]) 35 | { 36 | flag = true; 37 | break; 38 | } 39 | } 40 | return flag; 41 | } 42 | 43 | /// 44 | /// Check out the given type. If the type exist in typeMap, return true. 45 | /// 46 | /// 47 | /// The type. 48 | /// 49 | /// 50 | /// Type. 51 | /// 52 | public int containType(string type) 53 | { 54 | int value, returnInt = 2; 55 | if (this.typeMap.TryGetValue(type, out value)) 56 | { 57 | returnInt = value; 58 | } 59 | return returnInt; 60 | } 61 | 62 | //Init the typeMap 63 | private void initTypeMap() 64 | { 65 | Dictionary dic = new Dictionary(); 66 | dic.Add("uInt32", 0); 67 | dic.Add("sInt32", 0); 68 | dic.Add("int32", 0); 69 | dic.Add("double", 1); 70 | dic.Add("string", 2); 71 | dic.Add("float", 5); 72 | dic.Add("message", 2); 73 | 74 | this.typeMap = dic; 75 | } 76 | 77 | /// 78 | /// Reverses the order of bytes in the array 79 | /// 80 | public static void Reverse(byte[] bytes) 81 | { 82 | byte temp; 83 | for (int first = 0, last = bytes.Length - 1; first < last; first++, last--) 84 | { 85 | temp = bytes[first]; 86 | bytes[first] = bytes[last]; 87 | bytes[last] = temp; 88 | } 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protobuf/util/Util.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: dc8e63a6aad413f489578fd9cbb79784 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 95e11b69099d1f54bb3e37dfaad4da69 3 | folderAsset: yes 4 | timeCreated: 1473317717 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/HandShakeService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using SimpleJson; 4 | using System.Net; 5 | using System.Net.Sockets; 6 | 7 | namespace Pomelo.DotNetClient 8 | { 9 | public class HandShakeService 10 | { 11 | private Protocol protocol; 12 | private Action callback; 13 | 14 | public const string Version = "0.3.0"; 15 | public const string Type = "unity-socket"; 16 | 17 | 18 | public HandShakeService(Protocol protocol) 19 | { 20 | this.protocol = protocol; 21 | } 22 | 23 | public void request(JsonObject user, Action callback) 24 | { 25 | byte[] body = Encoding.UTF8.GetBytes(buildMsg(user).ToString()); 26 | 27 | protocol.send(PackageType.PKG_HANDSHAKE, body); 28 | 29 | this.callback = callback; 30 | } 31 | 32 | internal void invokeCallback(JsonObject data) 33 | { 34 | //Invoke the handshake callback 35 | if (callback != null) callback.Invoke(data); 36 | } 37 | 38 | public void ack() 39 | { 40 | protocol.send(PackageType.PKG_HANDSHAKE_ACK, new byte[0]); 41 | } 42 | 43 | private JsonObject buildMsg(JsonObject user) 44 | { 45 | if (user == null) user = new JsonObject(); 46 | 47 | JsonObject msg = new JsonObject(); 48 | 49 | //Build sys option 50 | JsonObject sys = new JsonObject(); 51 | sys["version"] = Version; 52 | sys["type"] = Type; 53 | 54 | //Build handshake message 55 | msg["sys"] = sys; 56 | msg["user"] = user; 57 | 58 | return msg; 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/HandShakeService.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 300cb44db57ebba49a4fa2ee66b76f34 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/HeartBeatService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Timers; 3 | 4 | namespace Pomelo.DotNetClient 5 | { 6 | public class HeartBeatService 7 | { 8 | int interval; 9 | public int timeout; 10 | Timer timer; 11 | DateTime lastTime; 12 | 13 | Protocol protocol; 14 | 15 | public HeartBeatService(int interval, Protocol protocol) 16 | { 17 | this.interval = interval * 1000; 18 | this.protocol = protocol; 19 | } 20 | 21 | internal void resetTimeout() 22 | { 23 | this.timeout = 0; 24 | lastTime = DateTime.Now; 25 | } 26 | 27 | public void sendHeartBeat(object source, ElapsedEventArgs e) 28 | { 29 | TimeSpan span = DateTime.Now - lastTime; 30 | timeout = (int)span.TotalMilliseconds; 31 | 32 | //check timeout 33 | if (timeout > interval * 2) 34 | { 35 | protocol.getPomeloClient().disconnect(); 36 | //stop(); 37 | return; 38 | } 39 | 40 | //Send heart beat 41 | protocol.send(PackageType.PKG_HEARTBEAT); 42 | } 43 | 44 | public void start() 45 | { 46 | if (interval < 1000) return; 47 | 48 | //start hearbeat 49 | this.timer = new Timer(); 50 | timer.Interval = interval; 51 | timer.Elapsed += new ElapsedEventHandler(sendHeartBeat); 52 | timer.Enabled = true; 53 | 54 | //Set timeout 55 | timeout = 0; 56 | lastTime = DateTime.Now; 57 | } 58 | 59 | public void stop() 60 | { 61 | if (this.timer != null) 62 | { 63 | this.timer.Enabled = false; 64 | this.timer.Dispose(); 65 | } 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/HeartBeatService.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 16db3ccec459640479216c66928254e0 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/Message.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using SimpleJson; 3 | 4 | namespace Pomelo.DotNetClient 5 | { 6 | public class Message 7 | { 8 | public MessageType type; 9 | public string route; 10 | public uint id; 11 | public JsonObject data; 12 | 13 | public Message(MessageType type, uint id, string route, JsonObject data) 14 | { 15 | this.type = type; 16 | this.id = id; 17 | this.route = route; 18 | this.data = data; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/Message.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 83ccf8db74e8a184ab0e0d8d1bb5418b 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/MessageProtocol.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Collections.Generic; 4 | using SimpleJson; 5 | using Pomelo.Protobuf; 6 | namespace Pomelo.DotNetClient 7 | { 8 | public class MessageProtocol 9 | { 10 | private Dictionary dict = new Dictionary(); 11 | private Dictionary abbrs = new Dictionary(); 12 | private JsonObject encodeProtos = new JsonObject(); 13 | private JsonObject decodeProtos = new JsonObject(); 14 | private Dictionary reqMap; 15 | private Protobuf.Protobuf protobuf; 16 | 17 | public const int MSG_Route_Limit = 255; 18 | public const int MSG_Route_Mask = 0x01; 19 | public const int MSG_Type_Mask = 0x07; 20 | 21 | public MessageProtocol(JsonObject dict, JsonObject serverProtos, JsonObject clientProtos) 22 | { 23 | ICollection keys = dict.Keys; 24 | 25 | foreach (string key in keys) 26 | { 27 | ushort value = Convert.ToUInt16(dict[key]); 28 | this.dict[key] = value; 29 | this.abbrs[value] = key; 30 | } 31 | 32 | protobuf = new Protobuf.Protobuf(clientProtos, serverProtos); 33 | this.encodeProtos = clientProtos; 34 | this.decodeProtos = serverProtos; 35 | 36 | this.reqMap = new Dictionary(); 37 | } 38 | 39 | public byte[] encode(string route, JsonObject msg) 40 | { 41 | return encode(route, 0, msg); 42 | } 43 | 44 | public byte[] encode(string route, uint id, JsonObject msg) 45 | { 46 | int routeLength = byteLength(route); 47 | if (routeLength > MSG_Route_Limit) 48 | { 49 | throw new Exception("Route is too long!"); 50 | } 51 | 52 | //Encode head 53 | //The maximus length of head is 1 byte flag + 4 bytes message id + route string length + 1byte 54 | byte[] head = new byte[routeLength + 6]; 55 | int offset = 1; 56 | byte flag = 0; 57 | 58 | if (id > 0) 59 | { 60 | byte[] bytes = Protobuf.Encoder.encodeUInt32(id); 61 | 62 | writeBytes(bytes, offset, head); 63 | flag |= ((byte)MessageType.MSG_REQUEST) << 1; 64 | offset += bytes.Length; 65 | } 66 | else 67 | { 68 | flag |= ((byte)MessageType.MSG_NOTIFY) << 1; 69 | } 70 | 71 | //Compress head 72 | if (dict.ContainsKey(route)) 73 | { 74 | ushort cmpRoute = dict[route]; 75 | writeShort(offset, cmpRoute, head); 76 | flag |= MSG_Route_Mask; 77 | offset += 2; 78 | } 79 | else 80 | { 81 | //Write route length 82 | head[offset++] = (byte)routeLength; 83 | 84 | //Write route 85 | writeBytes(Encoding.UTF8.GetBytes(route), offset, head); 86 | offset += routeLength; 87 | } 88 | 89 | head[0] = flag; 90 | 91 | //Encode body 92 | byte[] body; 93 | if (encodeProtos.ContainsKey(route)) 94 | { 95 | body = protobuf.encode(route, msg); 96 | } 97 | else 98 | { 99 | body = Encoding.UTF8.GetBytes(msg.ToString()); 100 | } 101 | 102 | //Construct the result 103 | byte[] result = new byte[offset + body.Length]; 104 | for (int i = 0; i < offset; i++) 105 | { 106 | result[i] = head[i]; 107 | } 108 | 109 | for (int i = 0; i < body.Length; i++) 110 | { 111 | result[offset + i] = body[i]; 112 | } 113 | 114 | //Add id to route map 115 | if (id > 0) reqMap.Add(id, route); 116 | 117 | return result; 118 | } 119 | 120 | public Message decode(byte[] buffer) 121 | { 122 | //Decode head 123 | //Get flag 124 | byte flag = buffer[0]; 125 | //Set offset to 1, for the 1st byte will always be the flag 126 | int offset = 1; 127 | 128 | //Get type from flag; 129 | MessageType type = (MessageType)((flag >> 1) & MSG_Type_Mask); 130 | uint id = 0; 131 | string route; 132 | 133 | if (type == MessageType.MSG_RESPONSE) 134 | { 135 | int length; 136 | id = (uint)Protobuf.Decoder.decodeUInt32(offset, buffer, out length); 137 | if (id <= 0 || !reqMap.ContainsKey(id)) 138 | { 139 | return null; 140 | } 141 | else 142 | { 143 | route = reqMap[id]; 144 | reqMap.Remove(id); 145 | } 146 | 147 | offset += length; 148 | } 149 | else if (type == MessageType.MSG_PUSH) 150 | { 151 | //Get route 152 | if ((flag & 0x01) == 1) 153 | { 154 | ushort routeId = readShort(offset, buffer); 155 | route = abbrs[routeId]; 156 | 157 | offset += 2; 158 | } 159 | else 160 | { 161 | byte length = buffer[offset]; 162 | offset += 1; 163 | 164 | route = Encoding.UTF8.GetString(buffer, offset, length); 165 | offset += length; 166 | } 167 | } 168 | else 169 | { 170 | return null; 171 | } 172 | 173 | //Decode body 174 | byte[] body = new byte[buffer.Length - offset]; 175 | for (int i = 0; i < body.Length; i++) 176 | { 177 | body[i] = buffer[i + offset]; 178 | } 179 | 180 | JsonObject msg; 181 | if (decodeProtos.ContainsKey(route)) 182 | { 183 | msg = protobuf.decode(route, body); 184 | } 185 | else 186 | { 187 | msg = (JsonObject)SimpleJson.SimpleJson.DeserializeObject(Encoding.UTF8.GetString(body)); 188 | } 189 | 190 | //Construct the message 191 | return new Message(type, id, route, msg); 192 | } 193 | 194 | private void writeInt(int offset, uint value, byte[] bytes) 195 | { 196 | bytes[offset] = (byte)(value >> 24 & 0xff); 197 | bytes[offset + 1] = (byte)(value >> 16 & 0xff); 198 | bytes[offset + 2] = (byte)(value >> 8 & 0xff); 199 | bytes[offset + 3] = (byte)(value & 0xff); 200 | } 201 | 202 | private void writeShort(int offset, ushort value, byte[] bytes) 203 | { 204 | bytes[offset] = (byte)(value >> 8 & 0xff); 205 | bytes[offset + 1] = (byte)(value & 0xff); 206 | } 207 | 208 | private ushort readShort(int offset, byte[] bytes) 209 | { 210 | ushort result = 0; 211 | 212 | result += (ushort)(bytes[offset] << 8); 213 | result += (ushort)(bytes[offset + 1]); 214 | 215 | return result; 216 | } 217 | 218 | private int byteLength(string msg) 219 | { 220 | return Encoding.UTF8.GetBytes(msg).Length; 221 | } 222 | 223 | private void writeBytes(byte[] source, int offset, byte[] target) 224 | { 225 | for (int i = 0; i < source.Length; i++) 226 | { 227 | target[offset + i] = source[i]; 228 | } 229 | } 230 | } 231 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/MessageProtocol.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: d88dd81c1da97394eaef63a17f36b509 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/MessageType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Pomelo.DotNetClient 4 | { 5 | public enum MessageType 6 | { 7 | MSG_REQUEST = 0, 8 | MSG_NOTIFY = 1, 9 | MSG_RESPONSE = 2, 10 | MSG_PUSH = 3 11 | } 12 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/MessageType.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: fc98a31126e6f95408155ed5e222a5e0 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/Package.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Pomelo.DotNetClient 4 | { 5 | public class Package 6 | { 7 | public PackageType type; 8 | public int length; 9 | public byte[] body; 10 | 11 | public Package(PackageType type, byte[] body) 12 | { 13 | this.type = type; 14 | this.length = body.Length; 15 | this.body = body; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/Package.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: a7c0fffb19979d246b928c02050f92bc 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/PackageProtocol.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Pomelo.DotNetClient 4 | { 5 | public class PackageProtocol 6 | { 7 | public const int HEADER_LENGTH = 4; 8 | 9 | public static byte[] encode(PackageType type) 10 | { 11 | return new byte[] { Convert.ToByte(type), 0, 0, 0 }; 12 | } 13 | 14 | public static byte[] encode(PackageType type, byte[] body) 15 | { 16 | int length = HEADER_LENGTH; 17 | 18 | if (body != null) length += body.Length; 19 | 20 | byte[] buf = new byte[length]; 21 | 22 | int index = 0; 23 | 24 | buf[index++] = Convert.ToByte(type); 25 | buf[index++] = Convert.ToByte(body.Length >> 16 & 0xFF); 26 | buf[index++] = Convert.ToByte(body.Length >> 8 & 0xFF); 27 | buf[index++] = Convert.ToByte(body.Length & 0xFF); 28 | 29 | while (index < length) 30 | { 31 | buf[index] = body[index - HEADER_LENGTH]; 32 | index++; 33 | } 34 | 35 | return buf; 36 | } 37 | 38 | public static Package decode(byte[] buf) 39 | { 40 | PackageType type = (PackageType)buf[0]; 41 | 42 | byte[] body = new byte[buf.Length - HEADER_LENGTH]; 43 | 44 | for (int i = 0; i < body.Length; i++) 45 | { 46 | body[i] = buf[i + HEADER_LENGTH]; 47 | } 48 | 49 | return new Package(type, body); 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/PackageProtocol.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 9ab0b827e90cc9c4e8d03a909cf37769 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/PackageTypes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Pomelo.DotNetClient 4 | { 5 | public enum PackageType 6 | { 7 | PKG_HANDSHAKE = 1, 8 | PKG_HANDSHAKE_ACK = 2, 9 | PKG_HEARTBEAT = 3, 10 | PKG_DATA = 4, 11 | PKG_KICK = 5 12 | } 13 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/PackageTypes.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: c4505fb57e46b234c9641423d3837327 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/Protocol.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using SimpleJson; 3 | using System.Text; 4 | 5 | namespace Pomelo.DotNetClient 6 | { 7 | public class Protocol 8 | { 9 | private MessageProtocol messageProtocol; 10 | private ProtocolState state; 11 | private Transporter transporter; 12 | private HandShakeService handshake; 13 | private HeartBeatService heartBeatService = null; 14 | private PomeloClient pc; 15 | 16 | public PomeloClient getPomeloClient() 17 | { 18 | return this.pc; 19 | } 20 | 21 | public Protocol(PomeloClient pc, System.Net.Sockets.Socket socket) 22 | { 23 | this.pc = pc; 24 | this.transporter = new Transporter(socket, this.processMessage); 25 | this.transporter.onDisconnect = onDisconnect; 26 | 27 | this.handshake = new HandShakeService(this); 28 | this.state = ProtocolState.start; 29 | } 30 | 31 | internal void start(JsonObject user, Action callback) 32 | { 33 | this.transporter.start(); 34 | this.handshake.request(user, callback); 35 | 36 | this.state = ProtocolState.handshaking; 37 | } 38 | 39 | //Send notify, do not need id 40 | internal void send(string route, JsonObject msg) 41 | { 42 | send(route, 0, msg); 43 | } 44 | 45 | //Send request, user request id 46 | internal void send(string route, uint id, JsonObject msg) 47 | { 48 | if (this.state != ProtocolState.working) return; 49 | 50 | byte[] body = messageProtocol.encode(route, id, msg); 51 | 52 | send(PackageType.PKG_DATA, body); 53 | } 54 | 55 | internal void send(PackageType type) 56 | { 57 | if (this.state == ProtocolState.closed) return; 58 | transporter.send(PackageProtocol.encode(type)); 59 | } 60 | 61 | //Send system message, these message do not use messageProtocol 62 | internal void send(PackageType type, JsonObject msg) 63 | { 64 | //This method only used to send system package 65 | if (type == PackageType.PKG_DATA) return; 66 | 67 | byte[] body = Encoding.UTF8.GetBytes(msg.ToString()); 68 | 69 | send(type, body); 70 | } 71 | 72 | //Send message use the transporter 73 | internal void send(PackageType type, byte[] body) 74 | { 75 | if (this.state == ProtocolState.closed) return; 76 | 77 | byte[] pkg = PackageProtocol.encode(type, body); 78 | 79 | transporter.send(pkg); 80 | } 81 | 82 | //Invoke by Transporter, process the message 83 | internal void processMessage(byte[] bytes) 84 | { 85 | Package pkg = PackageProtocol.decode(bytes); 86 | 87 | //Ignore all the message except handshading at handshake stage 88 | if (pkg.type == PackageType.PKG_HANDSHAKE && this.state == ProtocolState.handshaking) 89 | { 90 | 91 | //Ignore all the message except handshading 92 | JsonObject data = (JsonObject)SimpleJson.SimpleJson.DeserializeObject(Encoding.UTF8.GetString(pkg.body)); 93 | 94 | processHandshakeData(data); 95 | 96 | this.state = ProtocolState.working; 97 | 98 | } 99 | else if (pkg.type == PackageType.PKG_HEARTBEAT && this.state == ProtocolState.working) 100 | { 101 | this.heartBeatService.resetTimeout(); 102 | } 103 | else if (pkg.type == PackageType.PKG_DATA && this.state == ProtocolState.working) 104 | { 105 | this.heartBeatService.resetTimeout(); 106 | pc.processMessage(messageProtocol.decode(pkg.body)); 107 | } 108 | else if (pkg.type == PackageType.PKG_KICK) 109 | { 110 | this.getPomeloClient().disconnect(); 111 | this.close(); 112 | } 113 | } 114 | 115 | private void processHandshakeData(JsonObject msg) 116 | { 117 | //Handshake error 118 | if (!msg.ContainsKey("code") || !msg.ContainsKey("sys") || Convert.ToInt32(msg["code"]) != 200) 119 | { 120 | throw new Exception("Handshake error! Please check your handshake config."); 121 | } 122 | 123 | //Set compress data 124 | JsonObject sys = (JsonObject)msg["sys"]; 125 | 126 | JsonObject dict = new JsonObject(); 127 | if (sys.ContainsKey("dict")) dict = (JsonObject)sys["dict"]; 128 | 129 | JsonObject protos = new JsonObject(); 130 | JsonObject serverProtos = new JsonObject(); 131 | JsonObject clientProtos = new JsonObject(); 132 | 133 | if (sys.ContainsKey("protos")) 134 | { 135 | protos = (JsonObject)sys["protos"]; 136 | serverProtos = (JsonObject)protos["server"]; 137 | clientProtos = (JsonObject)protos["client"]; 138 | } 139 | 140 | messageProtocol = new MessageProtocol(dict, serverProtos, clientProtos); 141 | 142 | //Init heartbeat service 143 | int interval = 0; 144 | if (sys.ContainsKey("heartbeat")) interval = Convert.ToInt32(sys["heartbeat"]); 145 | heartBeatService = new HeartBeatService(interval, this); 146 | 147 | if (interval > 0) 148 | { 149 | heartBeatService.start(); 150 | } 151 | 152 | //send ack and change protocol state 153 | handshake.ack(); 154 | this.state = ProtocolState.working; 155 | 156 | //Invoke handshake callback 157 | JsonObject user = new JsonObject(); 158 | if (msg.ContainsKey("user")) user = (JsonObject)msg["user"]; 159 | handshake.invokeCallback(user); 160 | } 161 | 162 | //The socket disconnect 163 | private void onDisconnect() 164 | { 165 | this.pc.disconnect(); 166 | } 167 | 168 | internal void close() 169 | { 170 | transporter.close(); 171 | 172 | if (heartBeatService != null) heartBeatService.stop(); 173 | 174 | this.state = ProtocolState.closed; 175 | } 176 | } 177 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/Protocol.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 182aca7b9aeb21d4689204655b899989 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/ProtocolState.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Pomelo.DotNetClient 4 | { 5 | 6 | public enum ProtocolState 7 | { 8 | start = 1, // Just open, need to send handshaking 9 | handshaking = 2, // on handshaking process 10 | working = 3, // can receive and send data 11 | closed = 4, // on read body 12 | } 13 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/protocol/ProtocolState.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: de49d4b8424a57b4fad7820639bd5562 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/transport.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f6b405d1e378f5948a430d2edf1c63a4 3 | folderAsset: yes 4 | timeCreated: 1473317717 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/transport/TransportState.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Pomelo.DotNetClient 4 | { 5 | 6 | public enum TransportState 7 | { 8 | readHead = 1, // on read head 9 | readBody = 2, // on read body 10 | closed = 3 // connection closed, will ignore all the message and wait for clean up 11 | } 12 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/transport/TransportState.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: edbee285c21438d44a475c12d0eafdd0 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/transport/Transporter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Sockets; 3 | 4 | namespace Pomelo.DotNetClient 5 | { 6 | class StateObject 7 | { 8 | public const int BufferSize = 1024; 9 | internal byte[] buffer = new byte[BufferSize]; 10 | } 11 | 12 | public class Transporter 13 | { 14 | public const int HeadLength = 4; 15 | 16 | private Socket socket; 17 | private Action messageProcesser; 18 | 19 | //Used for get message 20 | private StateObject stateObject = new StateObject(); 21 | private TransportState transportState; 22 | private IAsyncResult asyncReceive; 23 | private IAsyncResult asyncSend; 24 | private bool onSending = false; 25 | private bool onReceiving = false; 26 | private byte[] headBuffer = new byte[4]; 27 | private byte[] buffer; 28 | private int bufferOffset = 0; 29 | private int pkgLength = 0; 30 | internal Action onDisconnect = null; 31 | 32 | //private TransportQueue _receiveQueue = new TransportQueue(); 33 | private System.Object _lock = new System.Object(); 34 | 35 | public Transporter(Socket socket, Action processer) 36 | { 37 | this.socket = socket; 38 | this.messageProcesser = processer; 39 | transportState = TransportState.readHead; 40 | } 41 | 42 | public void start() 43 | { 44 | this.receive(); 45 | } 46 | 47 | public void send(byte[] buffer) 48 | { 49 | if (this.transportState != TransportState.closed) 50 | { 51 | //string str = ""; 52 | //foreach (byte code in buffer) 53 | //{ 54 | // str += code.ToString(); 55 | //} 56 | //Console.WriteLine("send:" + buffer.Length + " " + str.Length + " " + str); 57 | this.asyncSend = socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(sendCallback), socket); 58 | 59 | this.onSending = true; 60 | } 61 | } 62 | 63 | private void sendCallback(IAsyncResult asyncSend) 64 | { 65 | //UnityEngine.Debug.Log("sendCallback " + this.transportState); 66 | if (this.transportState == TransportState.closed) return; 67 | socket.EndSend(asyncSend); 68 | this.onSending = false; 69 | } 70 | 71 | public void receive() 72 | { 73 | //Console.WriteLine("receive state : {0}, {1}", this.transportState, socket.Available); 74 | this.asyncReceive = socket.BeginReceive(stateObject.buffer, 0, stateObject.buffer.Length, SocketFlags.None, new AsyncCallback(endReceive), stateObject); 75 | this.onReceiving = true; 76 | } 77 | 78 | internal void close() 79 | { 80 | this.transportState = TransportState.closed; 81 | /*try{ 82 | if(this.onReceiving) socket.EndReceive (this.asyncReceive); 83 | if(this.onSending) socket.EndSend(this.asyncSend); 84 | }catch (Exception e){ 85 | Console.WriteLine(e.Message); 86 | }*/ 87 | } 88 | 89 | private void endReceive(IAsyncResult asyncReceive) 90 | { 91 | if (this.transportState == TransportState.closed) 92 | return; 93 | StateObject state = (StateObject)asyncReceive.AsyncState; 94 | Socket socket = this.socket; 95 | 96 | try 97 | { 98 | int length = socket.EndReceive(asyncReceive); 99 | 100 | this.onReceiving = false; 101 | 102 | if (length > 0) 103 | { 104 | processBytes(state.buffer, 0, length); 105 | //Receive next message 106 | if (this.transportState != TransportState.closed) receive(); 107 | } 108 | else 109 | { 110 | if (this.onDisconnect != null) this.onDisconnect(); 111 | } 112 | 113 | } 114 | catch (System.Net.Sockets.SocketException) 115 | { 116 | if (this.onDisconnect != null) 117 | this.onDisconnect(); 118 | } 119 | } 120 | 121 | internal void processBytes(byte[] bytes, int offset, int limit) 122 | { 123 | if (this.transportState == TransportState.readHead) 124 | { 125 | readHead(bytes, offset, limit); 126 | } 127 | else if (this.transportState == TransportState.readBody) 128 | { 129 | readBody(bytes, offset, limit); 130 | } 131 | } 132 | 133 | private bool readHead(byte[] bytes, int offset, int limit) 134 | { 135 | int length = limit - offset; 136 | int headNum = HeadLength - bufferOffset; 137 | 138 | if (length >= headNum) 139 | { 140 | //Write head buffer 141 | writeBytes(bytes, offset, headNum, bufferOffset, headBuffer); 142 | //Get package length 143 | pkgLength = (headBuffer[1] << 16) + (headBuffer[2] << 8) + headBuffer[3]; 144 | 145 | //Init message buffer 146 | buffer = new byte[HeadLength + pkgLength]; 147 | writeBytes(headBuffer, 0, HeadLength, buffer); 148 | offset += headNum; 149 | bufferOffset = HeadLength; 150 | this.transportState = TransportState.readBody; 151 | 152 | if (offset <= limit) processBytes(bytes, offset, limit); 153 | return true; 154 | } 155 | else 156 | { 157 | writeBytes(bytes, offset, length, bufferOffset, headBuffer); 158 | bufferOffset += length; 159 | return false; 160 | } 161 | } 162 | 163 | private void readBody(byte[] bytes, int offset, int limit) 164 | { 165 | int length = pkgLength + HeadLength - bufferOffset; 166 | if ((offset + length) <= limit) 167 | { 168 | writeBytes(bytes, offset, length, bufferOffset, buffer); 169 | offset += length; 170 | 171 | //Invoke the protocol api to handle the message 172 | this.messageProcesser.Invoke(buffer); 173 | this.bufferOffset = 0; 174 | this.pkgLength = 0; 175 | 176 | if (this.transportState != TransportState.closed) 177 | this.transportState = TransportState.readHead; 178 | if (offset < limit) 179 | processBytes(bytes, offset, limit); 180 | } 181 | else 182 | { 183 | writeBytes(bytes, offset, limit - offset, bufferOffset, buffer); 184 | bufferOffset += limit - offset; 185 | this.transportState = TransportState.readBody; 186 | } 187 | } 188 | 189 | private void writeBytes(byte[] source, int start, int length, byte[] target) 190 | { 191 | writeBytes(source, start, length, 0, target); 192 | } 193 | 194 | private void writeBytes(byte[] source, int start, int length, int offset, byte[] target) 195 | { 196 | for (int i = 0; i < length; i++) 197 | { 198 | target[offset + i] = source[start + i]; 199 | } 200 | } 201 | 202 | private void print(byte[] bytes, int offset, int length) 203 | { 204 | for (int i = offset; i < length; i++) 205 | Console.Write(Convert.ToString(bytes[i], 16) + " "); 206 | Console.WriteLine(); 207 | } 208 | } 209 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/transport/Transporter.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 16398747c50a96b4b97721540a8a2770 3 | timeCreated: 1473317717 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/transport/test.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 1d8032362f322e64ab2cfbaf4229cc37 3 | folderAsset: yes 4 | timeCreated: 1473317717 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/transport/test/TransportTest.cs: -------------------------------------------------------------------------------- 1 | using Pomelo.DotNetClient; 2 | using System; 3 | using System.Collections.Generic; 4 | using SimpleJson; 5 | 6 | namespace Pomelo.DotNetClient.Test 7 | { 8 | public class TransportTest 9 | { 10 | static List result = new List(); 11 | 12 | public static byte[] genBuffer(int count) 13 | { 14 | int size = count + 6; 15 | byte[] buffer = new byte[count + 10]; 16 | 17 | //Transporter tp = new Transporter(new Object(), protocol); 18 | buffer[0] = (byte)PackageType.PKG_DATA; 19 | buffer[1] = Convert.ToByte(size >> 16 & 0xFF); 20 | buffer[2] = Convert.ToByte(size >> 8 & 0xFF); 21 | buffer[3] = Convert.ToByte(size & 0xFF); 22 | 23 | //Generate message head 24 | //Response 25 | buffer[4] = 4; 26 | buffer[5] = 128; 27 | buffer[6] = 1; 28 | 29 | //Route length 30 | buffer[7] = 2; 31 | 32 | //Route 33 | buffer[8] = 62; 34 | buffer[9] = 72; 35 | 36 | Random random = new Random(); 37 | for (var i = 0; i < count; i++) buffer[10 + i] = (byte)random.Next(255); 38 | 39 | return buffer; 40 | } 41 | 42 | public static byte[] generateBuffers(int num, out List list) 43 | { 44 | int length = 100; 45 | int index = 0; 46 | byte[] result = new byte[(length + 10) * num]; 47 | list = new List(); 48 | 49 | for (int i = 0; i < num; i++) 50 | { 51 | byte[] bytes = genBuffer(length); 52 | list.Add(bytes); 53 | for (int j = 0; j < bytes.Length; j++) result[index++] = bytes[j]; 54 | } 55 | 56 | return result; 57 | } 58 | 59 | public static void Run() 60 | { 61 | int num = 10; 62 | int limit = 1000; 63 | 64 | Transporter tc = new Transporter(null, process); 65 | 66 | List list; 67 | 68 | byte[] buffer = generateBuffers(num, out list); 69 | 70 | int offset = 0; 71 | while (offset < buffer.Length) 72 | { 73 | int length = 200; 74 | length = (offset + length) > buffer.Length ? buffer.Length - offset : length; 75 | 76 | tc.processBytes(buffer, offset, offset + length); 77 | offset += length; 78 | } 79 | 80 | if (!check(list)) 81 | { 82 | Console.WriteLine("Transport test failed!"); 83 | } 84 | else 85 | { 86 | Console.WriteLine("Transport test success!"); 87 | } 88 | } 89 | 90 | public static void process(byte[] bytes) 91 | { 92 | result.Add(bytes); 93 | //Console.WriteLine("add bytes : {0}", result.Count); 94 | } 95 | 96 | public static void protocolProcess(byte[] bytes) 97 | { 98 | JsonObject dict = new JsonObject(); 99 | JsonObject serverProtos = new JsonObject(); 100 | JsonObject clientProtos = new JsonObject(); 101 | 102 | MessageProtocol messageProtocol = new MessageProtocol(dict, serverProtos, clientProtos); 103 | Package pkg = PackageProtocol.decode(bytes); 104 | 105 | messageProtocol.decode(pkg.body); 106 | } 107 | 108 | public static bool check(List list) 109 | { 110 | byte[][] origin = list.ToArray(); 111 | byte[][] target = result.ToArray(); 112 | 113 | if (origin.Length != target.Length) return false; 114 | 115 | for (int i = 0; i < origin.Length; i++) 116 | { 117 | byte[] o = origin[i]; 118 | byte[] t = result[i]; 119 | 120 | if (o.Length != t.Length) return false; 121 | for (int j = 0; j < o.Length; j++) 122 | { 123 | if (o[j] != t[j]) return false; 124 | } 125 | } 126 | 127 | return true; 128 | } 129 | } 130 | } -------------------------------------------------------------------------------- /Assets/Scripts/Networks/pomelo/transport/test/TransportTest.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: eb52e1d210f60f445944ceb0a32ec004 3 | timeCreated: 1473317718 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/RoundBall.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class RoundBall : MonoBehaviour { 5 | 6 | GameObject obj; 7 | float roundV = 60f; 8 | // Use this for initialization 9 | void Start () { 10 | this.obj = this.gameObject; 11 | } 12 | 13 | // Update is called once per frame 14 | void Update () { 15 | this.obj.transform.RotateAround(this.obj.transform.position, Vector3.up, roundV * Time.deltaTime); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Assets/Scripts/RoundBall.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: a1a89c7f56550cf478af943b4dbdf453 3 | timeCreated: 1473315888 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /Assets/Scripts/UILogic.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 7fed3552bb6904f43b274b106bfd9ca5 3 | folderAsset: yes 4 | timeCreated: 1473317888 5 | licenseType: Pro 6 | DefaultImporter: 7 | userData: 8 | assetBundleName: 9 | assetBundleVariant: 10 | -------------------------------------------------------------------------------- /Assets/Scripts/UILogic/ButtonClick.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class ButtonClick : MonoBehaviour { 5 | 6 | // Use this for initialization 7 | void Start () { 8 | 9 | } 10 | 11 | // Update is called once per frame 12 | void Update () { 13 | 14 | } 15 | 16 | public void onClick() { 17 | Debug.Log("btn click."); 18 | NetworkMgr.getInstance().newSocket(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Assets/Scripts/UILogic/ButtonClick.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 9ca17989db77c3b4782c32c0a30bce5d 3 | timeCreated: 1473317900 4 | licenseType: Pro 5 | MonoImporter: 6 | serializedVersion: 2 7 | defaultReferences: [] 8 | executionOrder: 0 9 | icon: {instanceID: 0} 10 | userData: 11 | assetBundleName: 12 | assetBundleVariant: 13 | -------------------------------------------------------------------------------- /ProjectSettings/AudioManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/AudioManager.asset -------------------------------------------------------------------------------- /ProjectSettings/ClusterInputManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/ClusterInputManager.asset -------------------------------------------------------------------------------- /ProjectSettings/DynamicsManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/DynamicsManager.asset -------------------------------------------------------------------------------- /ProjectSettings/EditorBuildSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/EditorBuildSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/EditorSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/EditorSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/GraphicsSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/GraphicsSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/InputManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/InputManager.asset -------------------------------------------------------------------------------- /ProjectSettings/NavMeshAreas.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/NavMeshAreas.asset -------------------------------------------------------------------------------- /ProjectSettings/NetworkManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/NetworkManager.asset -------------------------------------------------------------------------------- /ProjectSettings/Physics2DSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/Physics2DSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/ProjectSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/ProjectSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/ProjectVersion.txt: -------------------------------------------------------------------------------- 1 | m_EditorVersion: 5.3.6f1 2 | m_StandardAssetsVersion: 0 3 | -------------------------------------------------------------------------------- /ProjectSettings/QualitySettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/QualitySettings.asset -------------------------------------------------------------------------------- /ProjectSettings/TagManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/TagManager.asset -------------------------------------------------------------------------------- /ProjectSettings/TimeManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/TimeManager.asset -------------------------------------------------------------------------------- /ProjectSettings/UnityAdsSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/UnityAdsSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/UnityConnectSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shuidong/fastPomeloUnity/090105b72609367f50dbf0073623a31f0935aa80/ProjectSettings/UnityConnectSettings.asset -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fastPomeloUnity 2 | ## 背景介绍 3 | Pomelo是网易出品的一个基于node.js的游戏服务器框架(已经很久没维护了) 4 | 对于一些小型的游戏而言,socket方案采用node.js是一种成本较低的选择。 5 | 6 | Pomelo官方虽有unity的实现库与demo,但是在dns转换和socket连接的时候比较耗时, 7 | 会阻塞Unity的主线程,造成卡顿。 8 | ※fastPomeloUnity\Assets\Scripts\Networks\pomelo\client\PomeloClient.cs.old 是官方版本的代码,使用它替换PomeloClient.cs后再运行本项目,会发现转动的地球在初始化Pomelo时会卡顿 9 | 本项目对这方面进行了改善。 10 | 同时,项目还对Pomelo的消息收发进行了一定程度的封装,将游戏逻辑的代码与Pomelo部分剥离开。 11 | 12 | ## pomelo的修改 13 | 因此fastPomeloUnity\Assets\Scripts\Networks\pomelo\client\PomeloClient.cs做了如下修改: 14 | 1. 注释了Dns.GetHostEntry相关操作(这部分操作耗时 15 | 2. 通过BeginInvoke操作来完成socket的创建与连接,多线程,速度更快 16 | 17 | ## 流程原理 18 | 游戏启动后,Main脚本创建出Game对象(该对象负责控制游戏的总体逻辑,包括网络,音频,UI等) 19 | Game对象中会创建NetworkMgr对象,并在Update方法中执行networkMgr的相应更新方法,从消息队列中提取数据,然后根据配置好的路由捡出相应的处理器进行处理 20 | 21 | 那么,所谓的封装就是: 22 | A:把pomelo送来的消息放入 消息队列中, 23 | B:并且,在游戏启动初,就要为各个类型的消息 指派 对应的处理器 24 | 25 | 对于A部分,是在Pomelo.request和Pomelo.on 时做了手脚,让它的回调函数进入我们自己定义的逻辑 26 | 而B部分,则是通过BroadcastFact和CallbackFact 两个类来完成的。 27 | 28 | ##使用方法 29 | 1. 通过networkMgr的newSocket方法创建socket连接 30 | 2. 连接成功后就可以发送(request,notify)与接收数据(广播pomelo.on)了 31 | 3. 创建了Senders文件夹,下面的代码都是用来编写 发送逻辑的 32 | 4. 创建了Handlers文件夹,下面的代码都是用来编写 数据响应逻辑的 33 | 5. 在Routes类中罗列出各个route和响应的广播事件名称 34 | 6. 对于route的回调,在CallbackFact的registCallbacks方法中注册 35 | 7. 对于广播事件的回调,在BroadcastFact的registEvents中注册 36 | 37 | ## 联系方式 38 | LSD751@qq.com -------------------------------------------------------------------------------- /fastPomeloUnity.CSharp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | 10.0.20506 7 | 2.0 8 | {63FC5F8C-CDB9-0075-932D-C4C63E9FE9CA} 9 | Library 10 | Assembly-CSharp 11 | 512 12 | {E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 13 | .NETFramework 14 | v3.5 15 | Unity Subset v3.5 16 | 17 | Game:1 18 | StandaloneWindows:5 19 | 5.3.6f1 20 | 21 | 4 22 | 23 | 24 | pdbonly 25 | false 26 | Temp\UnityVS_bin\Debug\ 27 | Temp\UnityVS_obj\Debug\ 28 | prompt 29 | 4 30 | DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_3_6;UNITY_5_3;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_TEXTUREID_MAP;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_LOG_MIXED_STACKTRACE;ENABLE_UNITYWEBREQUEST;ENABLE_EVENT_QUEUE;ENABLE_CLUSTERINPUT;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE;UNITY_PRO_LICENSE 31 | false 32 | 33 | 34 | pdbonly 35 | false 36 | Temp\UnityVS_bin\Release\ 37 | Temp\UnityVS_obj\Release\ 38 | prompt 39 | 4 40 | TRACE;UNITY_5_3_OR_NEWER;UNITY_5_3_6;UNITY_5_3;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_TEXTUREID_MAP;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_LOG_MIXED_STACKTRACE;ENABLE_UNITYWEBREQUEST;ENABLE_EVENT_QUEUE;ENABLE_CLUSTERINPUT;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE;UNITY_PRO_LICENSE 41 | false 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | Library\UnityAssemblies\UnityEngine.dll 54 | 55 | 56 | Library\UnityAssemblies\UnityEngine.UI.dll 57 | 58 | 59 | Library\UnityAssemblies\UnityEngine.Networking.dll 60 | 61 | 62 | Library\UnityAssemblies\UnityEditor.dll 63 | 64 | 65 | Assets\Scripts\Networks\pomelo\lib\SimpleJson.dll 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /fastPomeloUnity.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2015 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "fastPomeloUnity.CSharp", "fastPomeloUnity.CSharp.csproj", "{63FC5F8C-CDB9-0075-932D-C4C63E9FE9CA}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|Any CPU = Debug|Any CPU 9 | Release|Any CPU = Release|Any CPU 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {63FC5F8C-CDB9-0075-932D-C4C63E9FE9CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 13 | {63FC5F8C-CDB9-0075-932D-C4C63E9FE9CA}.Debug|Any CPU.Build.0 = Debug|Any CPU 14 | {63FC5F8C-CDB9-0075-932D-C4C63E9FE9CA}.Release|Any CPU.ActiveCfg = Release|Any CPU 15 | {63FC5F8C-CDB9-0075-932D-C4C63E9FE9CA}.Release|Any CPU.Build.0 = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(SolutionProperties) = preSolution 18 | HideSolutionNode = FALSE 19 | EndGlobalSection 20 | EndGlobal 21 | --------------------------------------------------------------------------------