1 /* 2 * MsgTrans - Message Transport Framework for DLang. Based on TCP, WebSocket, UDP transmission protocol. 3 * 4 * Copyright (C) 2019 HuntLabs 5 * 6 * Website: https://www.msgtrans.org 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 12 module msgtrans.MessageTransport; 13 14 import msgtrans.MessageTransport; 15 import msgtrans.MessageHandler; 16 import msgtrans.SessionManager; 17 import msgtrans.executor.Executor; 18 import msgtrans.executor.ExecutorInfo; 19 20 import hunt.Exceptions; 21 import hunt.logging.ConsoleLogger; 22 23 import std.format; 24 25 26 enum SERVER_NAME_PREFIX = "SERVER-"; 27 enum CLIENT_NAME_PREFIX = "CLIENT-"; 28 29 /** 30 * 31 */ 32 abstract class MessageTransport { 33 private string _name; 34 private ExecutorInfo[uint] _executors; 35 private MessageHandler[uint] _messageHandlers; 36 37 this(string name) { 38 _name = name; 39 40 ExecutorInfo[] executors = Executor.getExecutors(_name); 41 foreach(ExecutorInfo e; executors) { 42 _executors[e.messageId()] = e; 43 } 44 } 45 46 string name() { 47 return _name; 48 } 49 50 void registerHandler(uint msgId, MessageHandler handler) { 51 auto itemPtr = msgId in _messageHandlers; 52 if(itemPtr is null) { 53 _messageHandlers[msgId] = handler; 54 } else { 55 // throw new Exception(format("Message handler confliction: %d", msgId)); 56 version(MSGTRANS_DEBUG) { 57 warningf("Message handler confliction: %d", msgId); 58 } 59 } 60 } 61 62 void deregisterHandler(uint msgId) { 63 auto itemPtr = msgId in _messageHandlers; 64 if(itemPtr is null) { 65 // throw new Exception(format("No message handler found: %d", msgId)); 66 version(MSGTRANS_DEBUG) { 67 warningf("No message handler found: %d", msgId); 68 } 69 } else { 70 _messageHandlers.remove(msgId); 71 } 72 } 73 74 MessageHandler getMessageHandler(uint id) { 75 auto itemPtr = id in _messageHandlers; 76 if(itemPtr is null) { 77 string msg = format("No message handler found for MessageID %d in peer %s", id, _name); 78 version(MSGTRANS_DEBUG) warning(msg); 79 return null; 80 } 81 return *itemPtr; 82 } 83 84 ExecutorInfo getExecutor(uint id) { 85 auto itemPtr = id in _executors; 86 if(itemPtr is null) { 87 string msg = format("No message handler found for MessageID %d in server %s", id, _name); 88 version(HUNT_DEBUG) warning(msg); 89 // throw new NoSuchElementException(msg); 90 return ExecutorInfo.init; 91 } 92 return *itemPtr; 93 } 94 95 SessionManager sessionManager() { return null; } 96 } 97 98 /** 99 * 100 */ 101 struct TransportServer { 102 enum NAME_PREFIX = "SERVER-"; 103 string name; 104 } 105 106 /** 107 * 108 */ 109 struct TransportClient { 110 enum NAME_PREFIX = "CLIENT-"; 111 string name; 112 }