|
| 1 | +using GodSharp.Sockets.Internal.Extension; |
| 2 | +using System; |
| 3 | +using System.Net.Sockets; |
| 4 | + |
| 5 | +namespace GodSharp.Sockets |
| 6 | +{ |
| 7 | + /// <summary> |
| 8 | + /// Extension class. |
| 9 | + /// </summary> |
| 10 | + public static class Extensions |
| 11 | + { |
| 12 | + /// <summary> |
| 13 | + /// Determines whether this instance is connected. |
| 14 | + /// </summary> |
| 15 | + /// <param name="client">The client.</param> |
| 16 | + /// <returns> |
| 17 | + /// <c>true</c> if the specified client is connected; otherwise, <c>false</c>. |
| 18 | + /// </returns> |
| 19 | + public static bool IsConnected(this SocketBase client) |
| 20 | + { |
| 21 | + return client.socket.IsConnected(); |
| 22 | + } |
| 23 | + |
| 24 | + /// <summary> |
| 25 | + /// Set <see cref="SocketClient"/> keep-alive option. |
| 26 | + /// </summary> |
| 27 | + /// <param name="client">The socket client.</param> |
| 28 | + /// <param name="on">if set to <c>true</c> [on].</param> |
| 29 | + /// <param name="time">The time.</param> |
| 30 | + /// <param name="interval">The interval.</param> |
| 31 | + /// <returns>return <see cref="bool"/> value of KeepAlive value.</returns> |
| 32 | + public static bool KeepAlive(this SocketBase client, bool on = true, uint time = 5000, uint interval = 5000) |
| 33 | + { |
| 34 | + try |
| 35 | + { |
| 36 | + byte[] inOptionValues = new byte[12]; |
| 37 | + |
| 38 | + uint off = (uint)(on ? 1 : 0); |
| 39 | + |
| 40 | + BitConverter.GetBytes(off).CopyTo(inOptionValues, 0); |
| 41 | + BitConverter.GetBytes(interval).CopyTo(inOptionValues, 4); |
| 42 | + BitConverter.GetBytes(interval).CopyTo(inOptionValues, 8); |
| 43 | + |
| 44 | + client.socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); |
| 45 | + |
| 46 | + object obj = client.socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive); |
| 47 | + |
| 48 | + return Convert.ToInt32(obj) == 1; |
| 49 | + } |
| 50 | + catch (Exception ex) |
| 51 | + { |
| 52 | + throw ex; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments