TcpSocketServerBase.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using SuperSocket.Common;
  9. using SuperSocket.SocketBase;
  10. using SuperSocket.SocketBase.Command;
  11. using SuperSocket.SocketBase.Protocol;
  12. namespace SuperSocket.SocketEngine
  13. {
  14. abstract class TcpSocketServerBase : SocketServerBase
  15. {
  16. private readonly byte[] m_KeepAliveOptionValues;
  17. private readonly byte[] m_KeepAliveOptionOutValues;
  18. private readonly int m_SendTimeOut;
  19. private readonly int m_ReceiveBufferSize;
  20. private readonly int m_SendBufferSize;
  21. public TcpSocketServerBase(IAppServer appServer, ListenerInfo[] listeners)
  22. : base(appServer, listeners)
  23. {
  24. var config = appServer.Config;
  25. uint dummy = 0;
  26. m_KeepAliveOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
  27. m_KeepAliveOptionOutValues = new byte[m_KeepAliveOptionValues.Length];
  28. //whether enable KeepAlive
  29. BitConverter.GetBytes((uint)1).CopyTo(m_KeepAliveOptionValues, 0);
  30. //how long will start first keep alive
  31. BitConverter.GetBytes((uint)(config.KeepAliveTime * 1000)).CopyTo(m_KeepAliveOptionValues, Marshal.SizeOf(dummy));
  32. //keep alive interval
  33. BitConverter.GetBytes((uint)(config.KeepAliveInterval * 1000)).CopyTo(m_KeepAliveOptionValues, Marshal.SizeOf(dummy) * 2);
  34. m_SendTimeOut = config.SendTimeOut;
  35. m_ReceiveBufferSize = config.ReceiveBufferSize;
  36. m_SendBufferSize = config.SendBufferSize;
  37. }
  38. protected IAppSession CreateSession(Socket client, ISocketSession session)
  39. {
  40. if (m_SendTimeOut > 0)
  41. client.SendTimeout = m_SendTimeOut;
  42. if (m_ReceiveBufferSize > 0)
  43. client.ReceiveBufferSize = m_ReceiveBufferSize;
  44. if (m_SendBufferSize > 0)
  45. client.SendBufferSize = m_SendBufferSize;
  46. //if (!Platform.SupportSocketIOControlByCodeEnum)
  47. // client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_KeepAliveOptionValues);
  48. //else
  49. //{
  50. // throw new NotImplementedException();
  51. //}
  52. client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_KeepAliveOptionValues);
  53. client.NoDelay = true;
  54. //client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
  55. client.LingerState = new LingerOption(false,0);
  56. return this.AppServer.CreateAppSession(session);
  57. }
  58. protected override ISocketListener CreateListener(ListenerInfo listenerInfo)
  59. {
  60. return new TcpAsyncSocketListener(listenerInfo);
  61. }
  62. }
  63. }