-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketUtil.cs
More file actions
71 lines (66 loc) · 2.18 KB
/
Copy pathSocketUtil.cs
File metadata and controls
71 lines (66 loc) · 2.18 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
namespace SocketTest.Common
{
/// <summary>
/// Copyright (C) 2017 yjq 版权所有。
/// 类名:SocketUtil.cs
/// 类属性:公共类(非静态)
/// 类功能描述:SocketUtil
/// 创建标识:yjq 2017/11/21 22:33:24
/// </summary>
public static class SocketUtil
{
public static IPAddress GetLocalIPV4()
{
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.First(m => m.AddressFamily == AddressFamily.InterNetwork);
}
/// <summary>
/// 创建socket
/// </summary>
/// <param name="receiveBufferSize">接收的buffer长度</param>
/// <param name="sendBufferSize">发送的buffer长度</param>
/// <returns>socket</returns>
public static Socket Create(int receiveBufferSize, int sendBufferSize)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
{
SendBufferSize = sendBufferSize,
ReceiveBufferSize = receiveBufferSize,
NoDelay = true,
Blocking = false
};
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
return socket;
}
public static void ShutDownCurrent(this Socket socket)
{
if (socket != null)
{
ExceptionUtil.Eat(() => socket.Shutdown(SocketShutdown.Both));
socket.CloseCurrent();
}
}
public static void CloseCurrent(this Socket socket)
{
if (socket != null)
{
ExceptionUtil.Eat(() => socket.Close(10000));
}
}
public static void DisposeCurrent(this SocketAsyncEventArgs e, EventHandler<SocketAsyncEventArgs> Completed)
{
if (e != null)
{
ExceptionUtil.Eat(() =>
{
e.Completed -= Completed;
e.AcceptSocket = null;
e.Dispose();
});
}
}
}
}