TcpSocketServerBase.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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.Logging;
  12. using SuperSocket.SocketBase.Protocol;
  13. namespace SuperSocket.SocketEngine
  14. {
  15. abstract class TcpSocketServerBase : SocketServerBase
  16. {
  17. private readonly byte[] m_KeepAliveOptionValues;
  18. private readonly byte[] m_KeepAliveOptionOutValues;
  19. private readonly int m_SendTimeOut;
  20. private readonly int m_ReceiveBufferSize;
  21. private readonly int m_SendBufferSize;
  22. public TcpSocketServerBase(IAppServer appServer, ListenerInfo[] listeners)
  23. : base(appServer, listeners)
  24. {
  25. var config = appServer.Config;
  26. uint dummy = 0;
  27. m_KeepAliveOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
  28. m_KeepAliveOptionOutValues = new byte[m_KeepAliveOptionValues.Length];
  29. //whether enable KeepAlive
  30. BitConverter.GetBytes((uint)1).CopyTo(m_KeepAliveOptionValues, 0);
  31. //how long will start first keep alive
  32. BitConverter.GetBytes((uint)(config.KeepAliveTime * 1000)).CopyTo(m_KeepAliveOptionValues, Marshal.SizeOf(dummy));
  33. //keep alive interval
  34. BitConverter.GetBytes((uint)(config.KeepAliveInterval * 1000)).CopyTo(m_KeepAliveOptionValues, Marshal.SizeOf(dummy) * 2);
  35. m_SendTimeOut = config.SendTimeOut;
  36. m_ReceiveBufferSize = config.ReceiveBufferSize;
  37. m_SendBufferSize = config.SendBufferSize;
  38. }
  39. protected IAppSession CreateSession(Socket client, ISocketSession session)
  40. {
  41. if (m_SendTimeOut > 0)
  42. client.SendTimeout = m_SendTimeOut;
  43. if (m_ReceiveBufferSize > 0)
  44. client.ReceiveBufferSize = m_ReceiveBufferSize;
  45. if (m_SendBufferSize > 0)
  46. client.SendBufferSize = m_SendBufferSize;
  47. if (!Platform.SupportSocketIOControlByCodeEnum)
  48. client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_KeepAliveOptionValues);
  49. else
  50. client.IOControl(IOControlCode.KeepAliveValues, m_KeepAliveOptionValues, m_KeepAliveOptionOutValues);
  51. client.NoDelay = true;
  52. client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
  53. return this.AppServer.CreateAppSession(session);
  54. }
  55. protected override ISocketListener CreateListener(ListenerInfo listenerInfo)
  56. {
  57. return new TcpAsyncSocketListener(listenerInfo);
  58. }
  59. }
  60. }