This repository was archived by the owner on Jun 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSocketHelpers.cs
134 lines (115 loc) · 2.32 KB
/
SocketHelpers.cs
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Assemblies.General
{
public static class SocketHelpers
{
static public async Task<bool> Send(TcpClient socket, byte [] abMessage)
{
return await Send(socket, abMessage, 0, abMessage.Length);
}
static public async Task<bool> Send(TcpClient socket, byte [] abMessage, int nStart)
{
return await Send(socket, abMessage, nStart, abMessage.Length - nStart);
}
static public async Task<bool> Send(TcpClient socket, byte [] abMessage, int nStart, int nLength)
{
bool fReturn = true;
try
{
var stream = socket.GetStream();
await stream.WriteAsync(abMessage, nStart, nLength);
await stream.FlushAsync();
}
catch (IOException)
{
fReturn = false;
}
catch (SocketException)
{
fReturn = false;
}
return fReturn;
}
static public async Task<bool> Send(TcpClient socket, string sMessage)
{
byte [] abMessage = System.Text.Encoding.ASCII.GetBytes(sMessage);
return await Send(socket, abMessage);
}
static public void Close(TcpClient socket)
{
if (socket == null)
return;
try
{
var stream = socket.GetStream();
try
{
stream.Flush();
}
catch (SocketException)
{
}
try
{
stream.Close();
}
catch (SocketException)
{
}
}
catch (SocketException)
{
}
catch (InvalidOperationException)
{
}
try
{
socket.Close();
}
catch (SocketException)
{
}
}
static public TcpClient CreateTcpClient(string sAddress, int nPort)
{
TcpClient client = null;
try
{
client = new TcpClient(sAddress, nPort);
}
catch (SocketException)
{
client = null;
}
return client;
}
static public TcpListener CreateTcpListener(int nPort)
{
TcpListener listener = null;
try
{
listener = new TcpListener(IPAddress.Any, nPort);
}
catch (SocketException)
{
listener = null;
}
return listener;
}
static public IPAddress GetLocalAddress()
{
var hostEntry = Dns.GetHostEntry(Dns.GetHostName());
if (hostEntry == null || hostEntry.AddressList.Length == 0)
{
return null;
}
return hostEntry.AddressList[0];
}
}
}