FuckFastStream.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. using CommonLang.Log;
  2. using CommonLang.Net;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.IO;
  9. using SuperSocket.SocketBase.Protocol;
  10. using SuperSocket.SocketBase;
  11. using SuperSocket.Facility.Protocol;
  12. using CommonLang.ByteOrder;
  13. using SuperSocket.SocketBase.Config;
  14. using System.Collections.Concurrent;
  15. using CommonLang;
  16. namespace Pomelo
  17. {
  18. public class FuckFastStream : FastStream
  19. {
  20. public static int MAX_REQUEST_LEN = 1024 * 1024 * 10; // 10M
  21. private static Logger log;
  22. private FuckAppServer acceptor;
  23. public FuckFastStream()
  24. {
  25. log = LoggerFactory.GetLogger("FuckStream");
  26. }
  27. public override void Start(FastStreamConfig fcfg, IZone zone)
  28. {
  29. try
  30. {
  31. this.acceptor = new FuckAppServer(zone);
  32. var cfg = new ServerConfig();
  33. {
  34. cfg.SyncSend = false;
  35. cfg.Port = fcfg.port;
  36. cfg.Mode = SocketMode.Tcp;
  37. cfg.DisableSessionSnapshot = true;
  38. cfg.LogCommand = false;
  39. cfg.LogBasicSessionActivity = false;
  40. cfg.Name = "FuckAppServer";
  41. cfg.ClearIdleSession = false;
  42. cfg.ClearIdleSessionInterval = 10;
  43. cfg.IdleSessionTimeOut = 1000000;
  44. cfg.SendingQueueSize = 40960;
  45. cfg.SendTimeOut = 5000;
  46. cfg.TextEncoding = "UTF-8";
  47. cfg.MaxConnectionNumber = 1000;
  48. cfg.MaxRequestLength = MAX_REQUEST_LEN;
  49. }
  50. if (acceptor.Setup(cfg))
  51. {
  52. this.acceptor.Start();
  53. log.Warn("start fuck stream on port:" + fcfg.port);
  54. }
  55. else
  56. {
  57. throw new Exception("Open Server Failed !");
  58. }
  59. }
  60. catch (Exception err)
  61. {
  62. log.Error(err.Message, err);
  63. throw;
  64. }
  65. }
  66. public override void Stop()
  67. {
  68. try
  69. {
  70. this.acceptor.Stop();
  71. }
  72. catch (Exception err)
  73. {
  74. log.Error(err.Message, err);
  75. throw;
  76. }
  77. try
  78. {
  79. this.acceptor.Dispose();
  80. }
  81. catch (Exception err)
  82. {
  83. log.Error(err.Message, err);
  84. throw;
  85. }
  86. }
  87. public override void Send(IFastSession session, string uid,string instanceId, ArraySegment<byte> data)
  88. {
  89. //FuckSession test = session as FuckSession;
  90. //Console.WriteLine(" - sendMsg - " + test.RemoteEndPoint.ToString());
  91. acceptor.SendInternal(session as FuckSession, uid, instanceId,data);
  92. }
  93. public override IFastSession GetSessionByID(string sessionID)
  94. {
  95. return acceptor.GetFuckSessionByID(sessionID);
  96. }
  97. //--------------------------------------------------------------------------------------------------------------------------------------------------------
  98. class FuckAppServer : AppServer<FuckSession, BinaryRequestInfo>
  99. {
  100. private Logger log = LoggerFactory.GetLogger("FuckAppServer");
  101. private ConcurrentDictionary<string, FuckSession> sessions = new ConcurrentDictionary<string, FuckSession>();
  102. private IZone zone;
  103. public FuckAppServer(IZone zone) : base(new FuckReceiveFilterFactory())
  104. {
  105. this.zone = zone;
  106. this.NewRequestReceived += AppServerImpl_NewRequestReceived;
  107. }
  108. public IFastSession GetFuckSessionByID(string sessionID)
  109. {
  110. FuckSession session;
  111. sessions.TryGetValue(sessionID, out session);
  112. return session;
  113. }
  114. protected override void OnStopped()
  115. {
  116. sessions.Clear();
  117. base.OnStopped();
  118. }
  119. protected override void OnNewSessionConnected(FuckSession session)
  120. {
  121. base.OnNewSessionConnected(session);
  122. log.Warn("A Session Connected : " + session);
  123. }
  124. protected override void OnSessionClosed(FuckSession session, CloseReason reason)
  125. {
  126. base.OnSessionClosed(session, reason);
  127. log.Warn("A Session Closed : " + session.ConnectorId + " : reason=" + reason);
  128. }
  129. private void AppServerImpl_NewRequestReceived(FuckSession session, BinaryRequestInfo bin)
  130. {
  131. try
  132. {
  133. //注意要捕获异常
  134. if (session.ConnectorId == null && "connetorId".Equals(bin.Key))
  135. {
  136. //connetorId为握手协议,表示了session的身份
  137. string connetorId = Encoding.UTF8.GetString(bin.Body);
  138. //ice绑定fastSocket
  139. if (!IceManager.instance().setFastSession(connetorId, session))
  140. {
  141. session.Close();
  142. return;
  143. }
  144. log.Warn("A Session Binded : " + session + " : connetorId=" + connetorId + ", info:" + session.RemoteEndPoint.ToString());
  145. session.ConnectorId = connetorId;
  146. sessions.AddOrUpdate(connetorId, session, (key, oldValue) => session);
  147. zone.onNetReconnect(connetorId, session);
  148. /*
  149. //客户端版本号信息
  150. using (var stream = new MemoryStream(5))
  151. {
  152. Composer.writeU8(stream, (ushort)200);
  153. Composer.writeU32(stream, (uint)bsVersion);
  154. session.Send(stream.GetBuffer(), 0, (int)stream.Position);
  155. }
  156. */
  157. }
  158. else
  159. {
  160. //发送数据到场景
  161. zone.PlayerReceive(bin.Key, bin.Body);
  162. }
  163. }
  164. catch (Exception e)
  165. {
  166. log.Error(e.Message, e);
  167. }
  168. }
  169. internal void SendInternal(FuckSession session, string uid, string instanceId, ArraySegment<byte> data)
  170. {
  171. try
  172. {
  173. byte[] bytesUid = System.Text.UTF8Encoding.UTF8.GetBytes(uid);
  174. //byte[] bytesInstanceId = System.Text.UTF8Encoding.UTF8.GetBytes(instanceId);
  175. int contentSize = 5 + bytesUid.Length + data.Count;// + bytesInstanceId.Length;
  176. //int lengthSize = Composer.calLengthSize(contentSize); // pomelo协议(待废弃)
  177. using (var stream = new MemoryStream(contentSize))
  178. {
  179. //composer head
  180. //Composer.writeLength(stream, contentSize, lengthSize);// pomelo协议(待废弃)
  181. //协议 head
  182. Composer.writeU8(stream, (ushort)bytesUid.Length);
  183. //Composer.writeU16(stream, (ushort)bytesInstanceId.Length);
  184. Composer.writeU32(stream, (uint)data.Count);
  185. //uid
  186. Composer.writeBytes(stream, bytesUid, 0, bytesUid.Length);
  187. //instanceId
  188. //Composer.writeBytes(stream, bytesInstanceId, 0, bytesInstanceId.Length);
  189. //data
  190. Composer.writeBytes(stream, data.Array, data.Offset, data.Count);
  191. //
  192. session.Send(stream.GetBuffer(), 0, (int)stream.Position);
  193. }
  194. }
  195. catch (Exception err)
  196. {
  197. log.Error(err.Message, err);
  198. session.Close(CloseReason.InternalError);
  199. }
  200. }
  201. }
  202. public class FuckSession : AppSession<FuckSession, BinaryRequestInfo>, IFastSession
  203. {
  204. public string ConnectorId { get; internal set; }
  205. public void doClose()
  206. {
  207. this.Close();
  208. }
  209. public override void Initialize(IAppServer<FuckSession, BinaryRequestInfo> appServer, ISocketSession socketSession)
  210. {
  211. base.Initialize(appServer, socketSession);
  212. socketSession.Client.NoDelay = true;
  213. }
  214. public bool IsConnected()
  215. {
  216. return this.Connected;
  217. }
  218. public string GetDescribe()
  219. {
  220. string des = "";
  221. try
  222. {
  223. des = this.LocalEndPoint.ToString();
  224. }
  225. catch(System.Exception e)
  226. {
  227. log.Warn("GetDescribe catch: " + e);
  228. }
  229. return des;
  230. }
  231. }
  232. class FuckReceiveFilterFactory : IReceiveFilterFactory<BinaryRequestInfo>
  233. {
  234. public IReceiveFilter<BinaryRequestInfo> CreateFilter(IAppServer appServer, IAppSession appSession, System.Net.IPEndPoint remoteEndPoint)
  235. {
  236. return new FuckReceiveFilter(appSession as FuckSession);
  237. }
  238. }
  239. class FuckReceiveFilter : FixedHeaderReceiveFilter<BinaryRequestInfo>
  240. {
  241. private readonly FuckSession appSession;
  242. public FuckReceiveFilter(FuckSession appSession) : base(6)
  243. {
  244. this.appSession = appSession;
  245. }
  246. protected override int GetBodyLengthFromHeader(byte[] header, int offset, int length)
  247. {
  248. int pos = offset;
  249. int idLength = LittleEdian.GetS16(header, ref pos);
  250. int bodyLength = LittleEdian.GetS32(header, ref pos);
  251. if (bodyLength > MAX_REQUEST_LEN)
  252. {
  253. appSession.Close(CloseReason.InternalError);
  254. throw new Exception(string.Format("FuckReceiveFilter bodyLength:{0} out of limit:{1} ", bodyLength, MAX_REQUEST_LEN));
  255. }
  256. return bodyLength + idLength;
  257. }
  258. protected override BinaryRequestInfo ResolveRequestInfo(ArraySegment<byte> header, byte[] bodyBuffer, int offset, int length)
  259. {
  260. int headerOffset = header.Offset;
  261. int idLength = LittleEdian.GetS16(header.Array, ref headerOffset);
  262. int dataLength = LittleEdian.GetS32(header.Array, ref headerOffset);
  263. if (length != idLength + dataLength)
  264. {
  265. appSession.Close(CloseReason.InternalError);
  266. throw new Exception("Body Length not equal idLength + dataLength");
  267. }
  268. string id = Encoding.UTF8.GetString(bodyBuffer, offset, idLength);
  269. byte[] body = new byte[dataLength];
  270. Buffer.BlockCopy(bodyBuffer, offset + idLength, body, 0, dataLength);
  271. return new BinaryRequestInfo(id, body);
  272. }
  273. }
  274. static class Composer
  275. {
  276. private const int LEFT_SHIFT_BITS = 1 << 7;
  277. public static int calLengthSize(int length)
  278. {
  279. int res = 0;
  280. while (length > 0)
  281. {
  282. length = length >> 7;
  283. res++;
  284. }
  285. return res;
  286. }
  287. public static void writeLength(Stream stream, int data, int size)
  288. {
  289. int offset = size - 1, b;
  290. byte[] bytes = new byte[size];
  291. for (; offset >= 0; offset--)
  292. {
  293. b = data % LEFT_SHIFT_BITS;
  294. if (offset < size - 1)
  295. {
  296. b |= 0x80;
  297. }
  298. bytes[offset] = (byte)b;
  299. data = data >> 7;
  300. }
  301. stream.Write(bytes, 0, bytes.Length);
  302. }
  303. public static void writeU8(Stream stream, UInt16 value)
  304. {
  305. stream.WriteByte((byte)(value));
  306. }
  307. public static void writeU16(Stream stream, UInt16 value)
  308. {
  309. stream.WriteByte((byte)(value));
  310. stream.WriteByte((byte)(value >> 8));
  311. }
  312. public static void writeU32(Stream stream, UInt32 value)
  313. {
  314. stream.WriteByte((byte)(value));
  315. stream.WriteByte((byte)(value >> 8));
  316. stream.WriteByte((byte)(value >> 16));
  317. stream.WriteByte((byte)(value >> 24));
  318. }
  319. public static void writeBytes(Stream stream, byte[] value, int offset, int count)
  320. {
  321. stream.Write(value, offset, count);
  322. }
  323. }
  324. }
  325. }