-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSocketLayerExtensions.cs
More file actions
43 lines (38 loc) · 1.89 KB
/
SocketLayerExtensions.cs
File metadata and controls
43 lines (38 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace RexStudios.CsharpExtensions
{
public static class SocketLayerExtensions
{
/// <summary>
/// Using IOControl code to configue socket KeepAliveValues for line disconnection detection(because default is toooo slow)
/// https://www.extensionmethod.net/csharp/net/setsocketkeepalivevalues
/// </summary>
/// <param name="tcpc">TcpClient</param>
/// <param name="KeepAliveTime">The keep alive time. (ms)</param>
/// <param name="KeepAliveInterval">The keep alive interval. (ms)</param>
public static void SetSocketKeepAliveValues(this TcpClient tcpc, int KeepAliveTime, int KeepAliveInterval)
{
//KeepAliveTime: default value is 2hr
//KeepAliveInterval: default value is 1s and Detect 5 times
uint dummy = 0; //lenth = 4
byte[] inOptionValues = new byte[System.Runtime.InteropServices.Marshal.SizeOf(dummy) * 3]; //size = lenth * 3 = 12
bool OnOff = true;
BitConverter.GetBytes((uint)(OnOff ? 1 : 0)).CopyTo(inOptionValues, 0);
BitConverter.GetBytes((uint)KeepAliveTime).CopyTo(inOptionValues, Marshal.SizeOf(dummy));
BitConverter.GetBytes((uint)KeepAliveInterval).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);
// of course there are other ways to marshal up this byte array, this is just one way
// call WSAIoctl via IOControl
// .net 1.1 type
//int SIO_KEEPALIVE_VALS = -1744830460; //(or 0x98000004)
//socket.IOControl(SIO_KEEPALIVE_VALS, inOptionValues, null);
// .net 3.5 type
tcpc.Client.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
}
}
}