-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketClient.cs
More file actions
252 lines (225 loc) · 8.7 KB
/
SocketClient.cs
File metadata and controls
252 lines (225 loc) · 8.7 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
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
//-------------------------------------------------------------------
// By Charlie Kindel
// http://www.kindel.com
// charlie@kindel.com
//
// Published under the MIT License.
// Source control on SourceForge
// http://sourceforge.net/projects/mcecontroller/
//-------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace MCEControl
{
/// <summary>
/// SocketClient implements our TCP/IP client.
///
/// Note this class can be invoked from mutliple threads simultaneously
/// and must be threadsafe.
///
/// </summary>
sealed public class SocketClient : ServiceBase, IDisposable
{
private readonly string _host = "";
private readonly int _port;
private readonly int _clientDelayTime;
public SocketClient(AppSettings settings)
{
_port = settings.ClientPort;
_host = settings.ClientHost;
_clientDelayTime = settings.ClientDelayTime;
}
// Finalize
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
~SocketClient()
{
Dispose();
}
private TcpClient _tcpClient;
private BackgroundWorker _bw;
private void Dispose(bool disposing)
{
if (disposing)
{
if (_bw != null)
{
_bw.CancelAsync();
_bw.Dispose();
_bw = null;
}
if (_tcpClient != null)
{
_tcpClient.Close();
_tcpClient = null;
}
}
}
public void Start(bool delay = false)
{
var currentCmd = new StringBuilder();
_tcpClient = new TcpClient();
_bw = new BackgroundWorker();
_bw.WorkerReportsProgress = false;
_bw.WorkerSupportsCancellation = true;
_bw.DoWork += (sender, args) =>
{
if (delay && _clientDelayTime > 0)
{
SetStatus(ServiceStatus.Sleeping);
Thread.Sleep(_clientDelayTime);
}
if (_bw == null || _bw.CancellationPending || _tcpClient == null)
return;
Connect();
};
_bw.RunWorkerAsync();
}
public void Stop()
{
Dispose(true);
if (CurrentStatus != ServiceStatus.Stopped)
SetStatus(ServiceStatus.Stopped);
}
// Send text to remote connection
public void Send(string newText)
{
if (!_tcpClient.Connected || _bw.CancellationPending) return;
try
{
byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(newText.Replace("\0xFF", "\0xFF\0xFF"));
_tcpClient.GetStream().Write(buf, 0, buf.Length);
}
catch (IOException ioe)
{
Error(ioe.Message);
}
}
private void Connect()
{
SetStatus(ServiceStatus.Started, string.Format("{0}:{1}", _host, _port));
IPEndPoint endPoint;
try
{
endPoint = new IPEndPoint(Dns.GetHostEntry(_host).AddressList[0], _port);
_tcpClient.BeginConnect(endPoint.Address, _port, ar =>
{
if (_tcpClient == null)
return;
try
{
_tcpClient.EndConnect(ar);
SetStatus(ServiceStatus.Connected);
StringBuilder sb = new StringBuilder();
while (_bw != null &&
!_bw.CancellationPending &&
CurrentStatus == ServiceStatus.Connected &&
_tcpClient != null &&
_tcpClient.Connected)
{
int input = _tcpClient.GetStream().ReadByte();
switch (input)
{
case (byte)'\r':
case (byte)'\n':
case (byte)'\0':
if (sb.Length > 0)
{
SendNotification(ServiceNotification.ReceivedData, ServiceStatus.Connected, new ClientReplyContext(_tcpClient), sb.ToString());
sb.Clear();
System.Threading.Thread.Sleep(100);
}
break;
case -1:
Error("No more data.");
return;
default:
sb.Append((char)input);
break;
}
}
}
catch (SocketException e)
{
switch (e.ErrorCode)
{
case 10061:
Error("Connection refused.");
break;
case 10060:
Error("Connection timed out.");
break;
default:
Error(string.Format("SocketException. ErrorCode: {0}{1}{2}", e.ErrorCode,
Environment.NewLine, e.Message));
break;
}
}
catch (IOException e)
{
var sockExcept = e.InnerException as SocketException;
if (sockExcept != null)
{
switch (sockExcept.ErrorCode)
{
case 10054:
Error("Remote connection has closed.");
break;
case 10053:
SetStatus(ServiceStatus.Stopped);
break;
case 10060:
Error("Connection timed out.");
break;
default:
Error(string.Format("SocketException (RecieveData). ErrorCode: {0}{1}{2}",
sockExcept.ErrorCode, Environment.NewLine, e.Message));
break;
}
}
else
{
Error(string.Format("IOException. {0}", e.Message));
}
}
}, null);
}
catch (SocketException e)
{
Error(string.Format("SocketException. ErrorCode: {0}{1}{2}", e.ErrorCode,
Environment.NewLine, e.Message));
_tcpClient.Close();
return;
}
Debug.WriteLine("BeginConnect returned");
}
#region Nested type: ClientReplyContext
public class ClientReplyContext : Reply
{
private readonly TcpClient _tcpClient;
// Constructor which takes a Socket and a client number
public ClientReplyContext(TcpClient tcpClient)
{
_tcpClient = tcpClient;
}
public override void Write(string text)
{
if (!_tcpClient.Connected) return;
byte[] buf = System.Text.Encoding.ASCII.GetBytes(text.Replace("\0xFF", "\0xFF\0xFF"));
_tcpClient.GetStream().Write(buf, 0, buf.Length);
}
}
#endregion
}
}