forked from Sovietmade/TwitchChatBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TcpConnection.cs
277 lines (237 loc) · 8.2 KB
/
TcpConnection.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
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.IO;
namespace TwitchChatBot
{
public class ReceivedDataArgs : EventArgs
{
private byte[] mData;
public ReceivedDataArgs ()
{
}
public ReceivedDataArgs (byte[] inData)
{
mData = inData;
}
public byte[] Data {
get{
return mData;
}
set{
mData = value;
}
}
}
public interface ITcpConnection
{
void Connect();
void SendMessage (string inMessage);
event EventHandler<ReceivedDataArgs> DataReceived;
}
public class Endpoint{
public string EndpointAddress
{
get;
set;
}
public int EndpointPort
{
get;
set;
}
public override string ToString ()
{
return string.Format ("{0}:{1}", EndpointAddress, EndpointPort);
}
}
/*
* V 0.TcpConnection class should perform TCP connection to the endpoint;
* V 1.Its should be able to connect *through* the proxy;
* V 2.Its should provide the means of communication with endpoint.
*/
public class TcpConnection : ITcpConnection
{
public TcpConnection ()
{
}
public bool Connected {
get{
return mTcpClient != null && mTcpClient.Connected;
}
}
public void Disconnect()
{
lock (mNetworkStreamLock)
{
if (Connected)
{
mNetworkStream.Close();
mTcpClient.Close();
mTcpClient = null;
mNetworkStream = null;
}
}
}
public void Connect ()
{
if (Connected) {
throw new InvalidOperationException ("Already Connected");
}
if (Destination == null) {
throw new InvalidOperationException("You should atleast specify destination endpoint");
}
if (mTcpClient == null) {
mTcpClient = new TcpClient();
}
/*
* As it connects it begin to read from stream http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.beginread(v=vs.110).aspx
* "When your application calls BeginRead, the system will wait until data is received or an error occurs, and then the system will use a separate thread to execute the specified callback method"
*/
if (Proxy == null) {
var result = mTcpClient.BeginConnect(Destination.EndpointAddress, Destination.EndpointPort, null, null);
var isSuccessful = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
if (!isSuccessful) {
mTcpClient = null;
mNetworkStream = null;
throw new TimeoutException("Failed to connect");
//throw new Exception("Failed to connect");
}
mTcpClient.EndConnect(result);
mTcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
//mTcpClient.Connect(Destination.EndpointAddress, Destination.EndpointPort);
mNetworkStream = mTcpClient.GetStream ();
mNetworkStream.BeginRead (Buffer, 0, Buffer.Length, new AsyncCallback (DataReceivedCallback), null);
} else {
var result = mTcpClient.BeginConnect(Proxy.EndpointAddress, Proxy.EndpointPort, null, null);
var isSuccessful = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
if (!isSuccessful)
{
mTcpClient = null;
mNetworkStream = null;
throw new TimeoutException("Failed to connect");
//throw new Exception("Failed to connect");
}
mTcpClient.EndConnect(result);
mTcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
//mTcpClient.Connect(Proxy.EndpointAddress, Proxy.EndpointPort);
mNetworkStream = mTcpClient.GetStream ();
mNetworkStream.BeginRead(Buffer, 0, Buffer.Length, new AsyncCallback (DataReceivedCallback), null);
string tunnelRequest = String.Format ("CONNECT {0} HTTP/1.1\r\nHost: {0}\r\n\r\n", Destination.ToString ());
SendMessage (tunnelRequest);
}
}
/*
* SendMessage appends the message queue with an inMessage
*/
public void SendMessage (string inMessage)
{
lock (MessageQ) {
MessageQ.Enqueue(inMessage);
}
SendMessageCallback(null);
}
/*
* SendMessageCallback transfer data to the destination through the NetworkStream
*/
private void SendMessageCallback (IAsyncResult result)
{
// result wont be null if current call to the SendMessageCallback is a continuation of BeginWrite execution
// result will be null if current call to the SendMessageCallback is a continuation of SendMessage execution
if (result != null && mNetworkStream!= null) {
mNetworkStream.EndWrite(result);
lock(MessageQ){
sending = false;
}
}
string CurrentMessage = null;
lock (MessageQ)
{
//There is a possibility, that call to SendMessageCallback was made through SendMessage,
//while another writing is in progress, so the call just returns, as inMessage was appended to the queue, and will be delivered in its turn
if (sending)
{
return;
}
if (MessageQ.Count != 0)
{
sending = true;
CurrentMessage = MessageQ.Dequeue();
//Console.WriteLine(CurrentMessage);
}
}
//CurrentMessage wont be null if the queue was not empty
//CurrentMessage will be null if the queue was empty
if (CurrentMessage != null && mNetworkStream != null)
{
try
{
if (mTcpClient.Connected)
{
mNetworkStream.BeginWrite(Encoding.UTF8.GetBytes(CurrentMessage), 0, Encoding.UTF8.GetBytes(CurrentMessage).Length, new AsyncCallback(SendMessageCallback), null);
}
else
{
EmergencyDisc();
return;
}
}
catch (NullReferenceException ex)
{
return;
}
}
}
/*
* Just passing received data to delegate and continue to read the stream
*/
private void DataReceivedCallback(IAsyncResult result)
{
lock (mNetworkStreamLock)
{
if (mNetworkStream != null)
{
int receivedDataLength = mNetworkStream.EndRead(result);
//Console.WriteLine("Received {0} bytes:\n {1}", receivedDataLength, Encoding.UTF8.GetString(Buffer));
byte[] ReceivedData = new byte[receivedDataLength];
Array.Copy(Buffer, ReceivedData, receivedDataLength);
OnDataReceived(new ReceivedDataArgs(ReceivedData));
try
{
if (mTcpClient.Connected)
{
mNetworkStream.BeginRead(Buffer, 0, Buffer.Length, new AsyncCallback(DataReceivedCallback), null);
}
else
{
EmergencyDisc();
return;
}
}
catch (NullReferenceException ex)
{
return;
}
}
}
}
protected virtual void OnDataReceived (ReceivedDataArgs ea)
{
if (DataReceived != null) {
DataReceived(this,ea);
}
}
public event EventHandler<ReceivedDataArgs> DataReceived;
public Action EmergencyDisc;
TcpClient mTcpClient;
NetworkStream mNetworkStream;
object mNetworkStreamLock = new object();
byte[] Buffer = new byte[2048];
Queue<string> MessageQ = new Queue<string>();
bool sending = false;
public Endpoint Proxy;
public Endpoint Destination;
}
}