Server.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. using System;
  2. using System.Collections.Generic;
  3. using CommonServer.Server;
  4. using CommonLang.Protocol;
  5. using System.Collections.Specialized;
  6. using SuperSocket.SocketBase;
  7. using SuperSocket.SocketBase.Protocol;
  8. using SuperSocket.SocketBase.Config;
  9. using System.Reflection;
  10. using CommonLang;
  11. using CommonLang.Log;
  12. using CommonLang.Net;
  13. using System.IO;
  14. using CommonLang.ByteOrder;
  15. namespace CommonServer.SSocket.SuperSocket
  16. {
  17. public class SocketAcceptor : IServer
  18. {
  19. private static Logger log = LoggerFactory.GetLogger("SSocket");
  20. private readonly INetPackageCodec _codec;
  21. private readonly IReceiveFilterFactory<BinaryRequestInfo> _filter;
  22. private readonly EmulateLagging _emu_lagging;
  23. private AppServerImpl _server;
  24. private string _connect_string;
  25. private ArraySegment<byte> _zero_segment = new ArraySegment<byte>(new byte[0]);
  26. internal long mTotalSentBytes;
  27. internal long mTotalRecvBytes;
  28. public string ClientConnectString { get { return _connect_string; } }
  29. public INetPackageCodec PackageCodec { get { return _codec; } }
  30. public long TotalSentBytes { get { return mTotalSentBytes; } }
  31. public long TotalRecvBytes { get { return mTotalRecvBytes; } }
  32. public int SessionCount { get { return _server.SessionCount; } }
  33. public bool EmulateLag
  34. {
  35. get { return _emu_lagging.EmulateLag; }
  36. }
  37. //-------------------------------------------------------------------------------------------------------------------------
  38. public SocketAcceptor(INetPackageCodec codec, IReceiveFilterFactory<BinaryRequestInfo> filter)
  39. {
  40. this._codec = codec;
  41. this._filter = filter;
  42. this._emu_lagging = new EmulateLagging();
  43. }
  44. public void Open(string host, int port, IServerListener listener)
  45. {
  46. CommonLang.Properties game_server_cfg = new CommonLang.Properties();
  47. game_server_cfg["SuperSocket.HOST"] = host;
  48. game_server_cfg["SuperSocket.PORT"] = port.ToString();
  49. game_server_cfg["SuperSocket.CLIENT_CONNECT_STRING"] = host + ":" + port;
  50. this.Open(game_server_cfg, listener);
  51. }
  52. /// <summary>
  53. /// <pre>
  54. /// SuperSocket.HOST = 192.168.1.1
  55. /// SuperSocket.PORT = 9527
  56. /// SuperSocket.CLIENT_CONNECT_STRING = 192.168.1.1:9527
  57. /// </pre>
  58. /// </summary>
  59. /// <param name="config"></param>
  60. /// <param name="listener"></param>
  61. public void Open(IDictionary<string, string> config, IServerListener listener)
  62. {
  63. string host = config["SuperSocket.HOST"];
  64. string port = config["SuperSocket.PORT"];
  65. if (host == null || port == null)
  66. {
  67. throw new Exception(@"Config Must Be Contains 'SuperSocket.HOST' and 'SuperSocket.PORT' fields !");
  68. }
  69. int dport = 0;
  70. if (!int.TryParse(port, out dport))
  71. {
  72. throw new Exception(@"Config 'SuperSocket.PORT' must be a digit value !");
  73. }
  74. this._connect_string = config["SuperSocket.CLIENT_CONNECT_STRING"];
  75. if (_connect_string == null)
  76. {
  77. throw new Exception(@"Config Must Be Contains 'SuperSocket.CLIENT_CONNECT_STRING' fields !");
  78. }
  79. ServerConfig cfg = new ServerConfig();
  80. cfg.SyncSend = false;
  81. cfg.Port = dport;
  82. cfg.Mode = SocketMode.Tcp;
  83. cfg.DisableSessionSnapshot = true;
  84. cfg.LogCommand = false;
  85. cfg.Name = "Server";
  86. cfg.ClearIdleSession = true;
  87. cfg.ClearIdleSessionInterval = 10;
  88. cfg.IdleSessionTimeOut = 10000;
  89. cfg.LogBasicSessionActivity = false;
  90. cfg.SendingQueueSize = 1000;
  91. cfg.SendTimeOut = 5000;
  92. cfg.TextEncoding = "UTF-8";
  93. cfg.MaxConnectionNumber = 1000;
  94. cfg.MaxRequestLength = 1024 * 100;
  95. foreach (string key in config.Keys)
  96. {
  97. try
  98. {
  99. if (key.StartsWith("SuperSocket."))
  100. {
  101. string value = config[key];
  102. string fname = key.Substring("SuperSocket.".Length);
  103. FieldInfo finfo = typeof(ServerConfig).GetField(fname);
  104. if (finfo != null)
  105. {
  106. finfo.SetValue(cfg, Parser.StringToObject(value.Trim(), finfo.FieldType));
  107. log.Info(string.Format(" {0} = {1}", key, value));
  108. }
  109. }
  110. }
  111. catch (Exception err) { }
  112. }
  113. this.Open(cfg, listener);
  114. }
  115. /// <summary>
  116. /// <pre>
  117. /// cfg.name: 服务器实例的名称;
  118. /// cfg.serverType: 服务器实例的类型的完整名称;
  119. /// cfg.serverTypeName: 所选用的服务器类型在 serverTypes 节点的名字,配置节点 serverTypes 用于定义所有可用的服务器类型,我们将在后面再做详细介绍;
  120. /// cfg.ip: 服务器监听的ip地址。你可以设置具体的地址,也可以设置为下面的值 Any - 所有的IPv4地址 IPv6Any - 所有的IPv6地址
  121. /// cfg.port: 服务器监听的端口;
  122. /// cfg.listenBacklog: 监听队列的大小;
  123. /// cfg.mode: Socket服务器运行的模式, Tcp (默认) 或者 Udp;
  124. /// cfg.disabled: 服务器实例是否禁用了;
  125. /// cfg.startupOrder: 服务器实例启动顺序, bootstrap 将按照此值的顺序来启动多个服务器实例;
  126. /// cfg.sendTimeOut: 发送数据超时时间;
  127. /// cfg.sendingQueueSize: 发送队列最大长度, 默认值为5;
  128. /// cfg.maxConnectionNumber: 可允许连接的最大连接数;
  129. /// cfg.receiveBufferSize: 接收缓冲区大小;
  130. /// cfg.sendBufferSize: 发送缓冲区大小;
  131. /// cfg.syncSend: 是否启用同步发送模式, 默认值: false;
  132. /// cfg.logCommand: 是否记录命令执行的记录;
  133. /// cfg.logBasicSessionActivity: 是否记录session的基本活动,如连接和断开;
  134. /// cfg.clearIdleSession: true 或 false, 是否定时清空空闲会话,默认值是 false;
  135. /// cfg.clearIdleSessionInterval: 清空空闲会话的时间间隔, 默认值是120, 单位为秒;
  136. /// cfg.idleSessionTimeOut: 会话空闲超时时间; 当此会话空闲时间超过此值,同时clearIdleSession被配置成true时,此会话将会被关闭; 默认值为300,单位为秒;
  137. /// cfg.security: Empty, Tls, Ssl3. Socket服务器所采用的传输层加密协议,默认值为空;
  138. /// cfg.maxRequestLength: 最大允许的请求长度,默认值为1024;
  139. /// cfg.textEncoding: 文本的默认编码,默认值是 ASCII;
  140. /// cfg.defaultCulture: 此服务器实例的默认 thread culture, 只在.Net 4.5中可用而且在隔离级别为 'None' 时无效;
  141. /// cfg.disableSessionSnapshot: 是否禁用会话快照, 默认值为 false.
  142. /// cfg.sessionSnapshotInterval: 会话快照时间间隔, 默认值是 5, 单位为秒;
  143. /// cfg.keepAliveTime: 网络连接正常情况下的keep alive数据的发送间隔, 默认值为 600, 单位为秒;
  144. /// cfg.keepAliveInterval: Keep alive失败之后, keep alive探测包的发送间隔,默认值为 60, 单位为秒;
  145. /// </pre>
  146. /// </summary>
  147. /// <param name="cfg"></param>
  148. /// <param name="listener"></param>
  149. public void Open(ServerConfig cfg, IServerListener listener)
  150. {
  151. this._server = new AppServerImpl(listener, this, _filter);
  152. if (_server.Setup(cfg))
  153. {
  154. this._emu_lagging.Start();
  155. this._server.Start();
  156. }
  157. else
  158. {
  159. throw new Exception("Open Server Failed !");
  160. }
  161. }
  162. public void Dispose()
  163. {
  164. _emu_lagging.Dispose();
  165. _server.Stop();
  166. _server.Dispose();
  167. }
  168. //-------------------------------------------------------------------------------------------------------------------------
  169. public void Broadcast(IMessage message)
  170. {
  171. foreach (ISession session in _server.GetAllSessions())
  172. {
  173. session.Send(message);
  174. }
  175. }
  176. public bool HasSession(ISession session)
  177. {
  178. return _server.GetSessionByID(session.ID) != null;
  179. }
  180. public ISession GetSessionByID(string sessionID)
  181. {
  182. return _server.GetSessionByID(sessionID) as ISession;
  183. }
  184. public IEnumerable<ISession> GetSessions()
  185. {
  186. return _server.GetAllSessions();
  187. }
  188. //-------------------------------------------------------------------------------------------------------------------------
  189. internal void SendDelay(Session session, byte[] buff, int offset, int length)
  190. {
  191. _emu_lagging.SendDelay(session, buff, offset, length);
  192. }
  193. public void SetEmulateLaggingMS(int min, int max)
  194. {
  195. _emu_lagging.SetEmulateLaggingMS(min, max);
  196. }
  197. public void GetEmulateLaggingMS(out int min, out int max)
  198. {
  199. _emu_lagging.GetEmulateLaggingMS(out min, out max);
  200. }
  201. //-------------------------------------------------------------------------------------------------------------------------
  202. protected internal virtual bool DoDecodeInternal(Session session, BinaryRequestInfo bin, out int bytes, out object message)
  203. {
  204. bytes = bin.Body.Length + 4;
  205. using (var ms = new MemoryStream(bin.Body))
  206. {
  207. object obj;
  208. if (_codec.doDecode(ms, out obj))
  209. {
  210. message = obj;
  211. return true;
  212. }
  213. }
  214. message = null;
  215. return false;
  216. }
  217. protected internal virtual bool DoEncodeInternal(Session session, object message, out ArraySegment<byte> bytes)
  218. {
  219. using (var ms = new MemoryStream(ServerFactory.SEND_BUFF_SIZE))
  220. {
  221. LittleEdian.PutS32(ms, 0);
  222. if (_codec.doEncode(ms, message))
  223. {
  224. int length = (int)ms.Position;
  225. int blen = length - 4;
  226. if (blen < 0)
  227. {
  228. throw new Exception(string.Format("sending trunk size={0} type={1}", blen, message.GetType().FullName));
  229. }
  230. ms.Position = 0;
  231. LittleEdian.PutS32(ms, blen);
  232. bytes = new ArraySegment<byte>(ms.GetBuffer(), 0, length);
  233. return true;
  234. }
  235. }
  236. bytes = _zero_segment;
  237. return false;
  238. }
  239. //-------------------------------------------------------------------------------------------------------------------------
  240. class AppServerImpl : AppServer<Session, BinaryRequestInfo>
  241. {
  242. internal readonly SocketAcceptor _owner;
  243. internal readonly IServerListener _listener;
  244. public AppServerImpl(IServerListener listener, SocketAcceptor owner, IReceiveFilterFactory<BinaryRequestInfo> filter)
  245. : base(filter)
  246. {
  247. this._owner = owner;
  248. this._listener = listener;
  249. this.NewRequestReceived += AppServerImpl_NewRequestReceived;
  250. }
  251. private void AppServerImpl_NewRequestReceived(Session session, BinaryRequestInfo requestInfo)
  252. {
  253. int bytes;
  254. object msg;
  255. if (_owner.DoDecodeInternal(session, requestInfo, out bytes, out msg))
  256. {
  257. _owner.mTotalRecvBytes += bytes;
  258. session.NewRequestReceived(bytes, msg);
  259. }
  260. }
  261. protected override bool RegisterSession(string sessionID, Session appSession)
  262. {
  263. if (base.RegisterSession(sessionID, appSession))
  264. {
  265. appSession.NewSessionConnected(_owner, _listener.OnSessionConnected(appSession), _owner.PackageCodec);
  266. return true;
  267. }
  268. return false;
  269. }
  270. protected override void OnNewSessionConnected(Session session)
  271. {
  272. base.OnNewSessionConnected(session);
  273. }
  274. protected override void OnStarted()
  275. {
  276. base.OnStarted();
  277. _listener.OnInit(_owner);
  278. }
  279. protected override void OnStopped()
  280. {
  281. base.OnStopped();
  282. _listener.OnDestory();
  283. }
  284. }
  285. }
  286. }