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. /*
  148. //客户端版本号信息
  149. using (var stream = new MemoryStream(5))
  150. {
  151. Composer.writeU8(stream, (ushort)200);
  152. Composer.writeU32(stream, (uint)bsVersion);
  153. session.Send(stream.GetBuffer(), 0, (int)stream.Position);
  154. }
  155. */
  156. }
  157. else
  158. {
  159. //发送数据到场景
  160. zone.PlayerReceive(bin.Key, bin.Body);
  161. }
  162. }
  163. catch (Exception e)
  164. {
  165. log.Error(e.Message, e);
  166. }
  167. }
  168. internal void SendInternal(FuckSession session, string uid, string instanceId, ArraySegment<byte> data)
  169. {
  170. try
  171. {
  172. byte[] bytesUid = System.Text.UTF8Encoding.UTF8.GetBytes(uid);
  173. //byte[] bytesInstanceId = System.Text.UTF8Encoding.UTF8.GetBytes(instanceId);
  174. int contentSize = 5 + bytesUid.Length + data.Count;// + bytesInstanceId.Length;
  175. //int lengthSize = Composer.calLengthSize(contentSize); // pomelo协议(待废弃)
  176. using (var stream = new MemoryStream(contentSize))
  177. {
  178. //composer head
  179. //Composer.writeLength(stream, contentSize, lengthSize);// pomelo协议(待废弃)
  180. //协议 head
  181. Composer.writeU8(stream, (ushort)bytesUid.Length);
  182. //Composer.writeU16(stream, (ushort)bytesInstanceId.Length);
  183. Composer.writeU32(stream, (uint)data.Count);
  184. //uid
  185. Composer.writeBytes(stream, bytesUid, 0, bytesUid.Length);
  186. //instanceId
  187. //Composer.writeBytes(stream, bytesInstanceId, 0, bytesInstanceId.Length);
  188. //data
  189. Composer.writeBytes(stream, data.Array, data.Offset, data.Count);
  190. //
  191. session.Send(stream.GetBuffer(), 0, (int)stream.Position);
  192. }
  193. }
  194. catch (Exception err)
  195. {
  196. log.Error(err.Message, err);
  197. session.Close(CloseReason.InternalError);
  198. }
  199. }
  200. }
  201. class FuckSession : AppSession<FuckSession, BinaryRequestInfo>, IFastSession
  202. {
  203. public string ConnectorId { get; internal set; }
  204. public void doClose()
  205. {
  206. this.Close();
  207. }
  208. public override void Initialize(IAppServer<FuckSession, BinaryRequestInfo> appServer, ISocketSession socketSession)
  209. {
  210. base.Initialize(appServer, socketSession);
  211. socketSession.Client.NoDelay = true;
  212. }
  213. public bool IsConnected()
  214. {
  215. return this.Connected;
  216. }
  217. public string GetDescribe()
  218. {
  219. string des = "";
  220. try
  221. {
  222. des = this.LocalEndPoint.ToString();
  223. }
  224. catch(System.Exception e)
  225. {
  226. log.Warn("GetDescribe catch: " + e);
  227. }
  228. return des;
  229. }
  230. }
  231. class FuckReceiveFilterFactory : IReceiveFilterFactory<BinaryRequestInfo>
  232. {
  233. public IReceiveFilter<BinaryRequestInfo> CreateFilter(IAppServer appServer, IAppSession appSession, System.Net.IPEndPoint remoteEndPoint)
  234. {
  235. return new FuckReceiveFilter(appSession as FuckSession);
  236. }
  237. }
  238. class FuckReceiveFilter : FixedHeaderReceiveFilter<BinaryRequestInfo>
  239. {
  240. private readonly FuckSession appSession;
  241. public FuckReceiveFilter(FuckSession appSession) : base(6)
  242. {
  243. this.appSession = appSession;
  244. }
  245. protected override int GetBodyLengthFromHeader(byte[] header, int offset, int length)
  246. {
  247. int pos = offset;
  248. int idLength = LittleEdian.GetS16(header, ref pos);
  249. int bodyLength = LittleEdian.GetS32(header, ref pos);
  250. if (bodyLength > MAX_REQUEST_LEN)
  251. {
  252. appSession.Close(CloseReason.InternalError);
  253. throw new Exception(string.Format("FuckReceiveFilter bodyLength:{0} out of limit:{1} ", bodyLength, MAX_REQUEST_LEN));
  254. }
  255. return bodyLength + idLength;
  256. }
  257. protected override BinaryRequestInfo ResolveRequestInfo(ArraySegment<byte> header, byte[] bodyBuffer, int offset, int length)
  258. {
  259. int headerOffset = header.Offset;
  260. int idLength = LittleEdian.GetS16(header.Array, ref headerOffset);
  261. int dataLength = LittleEdian.GetS32(header.Array, ref headerOffset);
  262. if (length != idLength + dataLength)
  263. {
  264. appSession.Close(CloseReason.InternalError);
  265. throw new Exception("Body Length not equal idLength + dataLength");
  266. }
  267. string id = Encoding.UTF8.GetString(bodyBuffer, offset, idLength);
  268. byte[] body = new byte[dataLength];
  269. Buffer.BlockCopy(bodyBuffer, offset + idLength, body, 0, dataLength);
  270. return new BinaryRequestInfo(id, body);
  271. }
  272. }
  273. static class Composer
  274. {
  275. private const int LEFT_SHIFT_BITS = 1 << 7;
  276. public static int calLengthSize(int length)
  277. {
  278. int res = 0;
  279. while (length > 0)
  280. {
  281. length = length >> 7;
  282. res++;
  283. }
  284. return res;
  285. }
  286. public static void writeLength(Stream stream, int data, int size)
  287. {
  288. int offset = size - 1, b;
  289. byte[] bytes = new byte[size];
  290. for (; offset >= 0; offset--)
  291. {
  292. b = data % LEFT_SHIFT_BITS;
  293. if (offset < size - 1)
  294. {
  295. b |= 0x80;
  296. }
  297. bytes[offset] = (byte)b;
  298. data = data >> 7;
  299. }
  300. stream.Write(bytes, 0, bytes.Length);
  301. }
  302. public static void writeU8(Stream stream, UInt16 value)
  303. {
  304. stream.WriteByte((byte)(value));
  305. }
  306. public static void writeU16(Stream stream, UInt16 value)
  307. {
  308. stream.WriteByte((byte)(value));
  309. stream.WriteByte((byte)(value >> 8));
  310. }
  311. public static void writeU32(Stream stream, UInt32 value)
  312. {
  313. stream.WriteByte((byte)(value));
  314. stream.WriteByte((byte)(value >> 8));
  315. stream.WriteByte((byte)(value >> 16));
  316. stream.WriteByte((byte)(value >> 24));
  317. }
  318. public static void writeBytes(Stream stream, byte[] value, int offset, int count)
  319. {
  320. stream.Write(value, offset, count);
  321. }
  322. }
  323. }
  324. }