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 using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
namespace WinPhoneFtp.FtpService
{
public sealed class TcpClientSocket : IDisposable
{
String IpAddress = String.Empty;
String Port = String.Empty;
StreamSocket streamSocket = null;
String SocketName = String.Empty;
DataWriter TcpStreamWriter = null;
Boolean IsConnectionClosedByRemoteHost = false;
UInt32 ReadBufferLength = 0;
Boolean IsSocketConnected = false;
Logger logger = null;
Dispatcher UIDispatcher = null;
DataReader TcpStreamReader = null;
public event EventHandler<DataReceivedEventArgs> DataReceived;
public event EventHandler<SocketClosedEventArgs> SocketClosed;
public event EventHandler<ErrorOccuredEventArgs> ErrorOccured;
public event EventHandler SocketConnected;
public TcpClientSocket(String IpAddress, String Port, Dispatcher UIDispatcher)
: this(IpAddress, Port, 512, "NoName", UIDispatcher)
{
}
public TcpClientSocket(String IpAddress, String Port, UInt32 ReadBufferLength, Dispatcher UIDispatcher)
: this(IpAddress, Port, ReadBufferLength, "NoName", UIDispatcher)
{
}
public TcpClientSocket(String IpAddress, String Port, String SocketName, Dispatcher UIDispatcher)
: this(IpAddress, Port, 512, SocketName, UIDispatcher)
{
}
public TcpClientSocket(String IpAddress, String Port, UInt32 ReadBufferLength, String SocketName, Dispatcher UIDispatcher)
{
this.UIDispatcher = UIDispatcher != null ? UIDispatcher : Deployment.Current.Dispatcher;
logger = Logger.GetDefault(UIDispatcher);
this.IpAddress = IpAddress;
this.Port = Port;
this.SocketName = SocketName;
this.ReadBufferLength = ReadBufferLength;
//logger.AddLog(String.Format("Creating new TCP Socket {0}. IPAddress: {1}, Port: {2}", SocketName, IpAddress, Port));
}
public async Task PrepareSocketAsync()
{
streamSocket = new StreamSocket();
//logger.AddLog(String.Format("Connecting {0} socket at IPAddress: {1}, Port: {2}", SocketName, IpAddress, Port));
try
{
await streamSocket.ConnectAsync(new Windows.Networking.HostName(IpAddress), Port);
}
catch (Exception ex)
{
//logger.AddLog("Unable to connect to remote connection");
RaiseErrorOccuredEvent(ex);
return;
}
//logger.AddLog("Connected");
TcpStreamWriter = new DataWriter(streamSocket.OutputStream);
IsSocketConnected = true;
try
{
await Task.Factory.StartNew(stream =>
{
TcpStreamReader = new DataReader((IInputStream)stream);
TcpStreamReader.InputStreamOptions = InputStreamOptions.Partial;
try
{
DataReaderLoadOperation loadOperation = TcpStreamReader.LoadAsync(ReadBufferLength);
loadOperation.Completed = new Windows.Foundation.AsyncOperationCompletedHandler<UInt32>(LoadCompleted);
}
catch (Exception ex)
{
RaiseErrorOccuredEvent(ex);
}
}, streamSocket.InputStream);
}
catch
{
//logger.AddLog("Asynchronous Read Operation Canceled");
}
RaiseSocketConnectedEvent();
}
private void LoadCompleted(Windows.Foundation.IAsyncOperation<uint> asyncInfo, Windows.Foundation.AsyncStatus asyncStatus)
{
switch (asyncStatus)
{
case Windows.Foundation.AsyncStatus.Canceled:
//logger.AddLog("Data load operation canceled");
break;
case Windows.Foundation.AsyncStatus.Completed:
//logger.AddLog("Data load operation completed");
if (TcpStreamReader.UnconsumedBufferLength.Equals(0))
{
if (IsSocketConnected)
{
//logger.AddLog("Connection closed by remote host. Exiting");
IsSocketConnected = false;
IsConnectionClosedByRemoteHost = true;
CloseSocket();
}
}
else
{
IBuffer buffer = TcpStreamReader.DetachBuffer();
RaiseDataReceivedEvent(buffer.ToArray());
DataReaderLoadOperation loadOperation = TcpStreamReader.LoadAsync(ReadBufferLength);
loadOperation.Completed = new Windows.Foundation.AsyncOperationCompletedHandler<UInt32>(LoadCompleted);
}
break;
case Windows.Foundation.AsyncStatus.Error:
//logger.AddLog("Exception in data load operation");
IsSocketConnected = false;
if (asyncInfo.ErrorCode.HResult.Equals(-2147014842))
{
IsConnectionClosedByRemoteHost = true;
}
else
{
RaiseErrorOccuredEvent(asyncInfo.ErrorCode);
}
CloseSocket();
break;
case Windows.Foundation.AsyncStatus.Started:
//logger.AddLog("Data load operation started");
break;
}
}
public async Task SendDataAsync(byte[] data)
{
if (TcpStreamWriter != null)
{
TcpStreamWriter.WriteBytes(data);
await TcpStreamWriter.StoreAsync();
}
}
public async Task SendDataAsync(String data)
{
if (TcpStreamWriter != null)
{
TcpStreamWriter.WriteString(data);
await TcpStreamWriter.StoreAsync();
}
}
[System.Security.SecuritySafeCritical()]
public void CloseSocket()
{
IsSocketConnected = false;
//logger.AddLog(String.Format("Closing {0} socket", SocketName));
if (TcpStreamWriter != null)
{
//loadOperation.Close();
TcpStreamWriter.Dispose();
TcpStreamWriter = null;
}
if (streamSocket != null)
{
DataReceived = null;
ErrorOccured = null;
if (!IsConnectionClosedByRemoteHost)
{
//loadOperation.Cancel();
RaiseSocketClosedEvent(SocketCloseReason.ClosedFromLocalHost);
}
else
{
RaiseSocketClosedEvent(SocketCloseReason.ClosedByRemoteHost);
}
SocketClosed = null;
streamSocket.Dispose();
streamSocket = null;
}
}
private void RaiseDataReceivedEvent(Byte[] data)
{
if (DataReceived != null)
{
DataReceived(this, new DataReceivedEventArgs(data));
}
}
private void RaiseSocketClosedEvent(SocketCloseReason CloseReason)
{
if (SocketClosed != null)
{
SocketClosed(this, new SocketClosedEventArgs(CloseReason));
}
}
private void RaiseErrorOccuredEvent(Exception ExceptionObject)
{
if (ErrorOccured != null)
{
ErrorOccured(this, new ErrorOccuredEventArgs(ExceptionObject));
}
}
private void RaiseSocketConnectedEvent()
{
if (SocketConnected != null)
{
SocketConnected(this, EventArgs.Empty);
}
}
public async void Dispose()
{
if (TcpStreamWriter != null)
{
await TcpStreamWriter.FlushAsync();
TcpStreamWriter.Dispose();
}
if (streamSocket != null)
{
streamSocket.Dispose();
}
}
}
}