-
Notifications
You must be signed in to change notification settings - Fork 0
/
SocketClient.cs
178 lines (145 loc) · 4.92 KB
/
SocketClient.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
using System;
using System.Net;
using System.Net.Sockets;
namespace Megamind.Net.Sockets
{
public class SocketClient
{
#region Data
// client objects
readonly byte[] _buffer;
readonly Socket _socket;
// A delegate type for hooking up change notifications.
public delegate void ClientEventHandler(object sender);
public delegate void DataEventHandler(object sender, SocketEventArgs e);
// public events
public event ClientEventHandler OnConnected;
public event ClientEventHandler OnDisconnected;
public event DataEventHandler OnAsyncConnectFailed;
public event DataEventHandler OnDataSending;
public event DataEventHandler OnDataReceived;
public event DataEventHandler OnConnectionLost;
#endregion
#region Properties
public int Port { get; set; }
public string Host { get; set; }
public bool IsConnected { get; private set; }
public EndPoint LocalEndPoint
{
get { return _socket.LocalEndPoint; }
}
public EndPoint RemoteEndPoint
{
get { return _socket.RemoteEndPoint; }
}
public string EndPointString
{
get { return string.Format("{0} -> {1}", _socket.LocalEndPoint, _socket.RemoteEndPoint); }
}
#endregion
#region ctor
public SocketClient(string host, int port, int buffersize = 0xFFFF)
{
Host = host;
Port = port;
_buffer = new byte[buffersize]; //0xFFFF = 64k
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public virtual void Connect()
{
_socket.Connect(Host, Port);
IsConnected = true;
ClientConnected();
_socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceiveCallback_Async, null);
}
public virtual void ConnectAsync()
{
_socket.BeginConnect(Host, Port, ConnectCallback_Async, null);
}
private void ConnectCallback_Async(IAsyncResult ar)
{
try
{
_socket.EndConnect(ar);
IsConnected = true;
ClientConnected();
_socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceiveCallback_Async, null);
}
catch (Exception ex)
{
AsyncConnectFailed(ex);
}
}
public virtual void Disconnect()
{
IsConnected = false;
ClientDisconnected();
if (_socket == null) return;
_socket.Shutdown(SocketShutdown.Both);
_socket.Close();
}
#endregion
#region Read Write
public int Send(byte[] data)
{
return _socket.Send(data);
}
public int SendData(byte[] data)
{
SocketDataSending(data);
return _socket.Send(data);
}
private void ReceiveCallback_Async(IAsyncResult ar)
{
//disconnect from here, protect Object Disposed Exception
if (!IsConnected) return;
try
{
// exception on socket close or connection lost
var bytesToRead = _socket.EndReceive(ar);
if (bytesToRead == 0) //disconnect from remote
{
ConnectionLost(new Exception("Disconnected from remote socket"));
Disconnect();
return;
}
var data = new byte[bytesToRead];
Array.Copy(_buffer, data, bytesToRead);
SocketDataReceived(data);
_socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceiveCallback_Async, null);
}
catch (Exception ex) //conenction lost
{
ConnectionLost(ex);
Disconnect();
}
}
#endregion
#region Event Handlers
public virtual void AsyncConnectFailed(Exception ex)
{
OnAsyncConnectFailed?.Invoke(this, new SocketEventArgs(ex.Message));
}
public virtual void ClientConnected()
{
OnConnected?.Invoke(this);
}
public virtual void ClientDisconnected()
{
OnDisconnected?.Invoke(this);
}
public virtual void SocketDataSending(byte[] data)
{
OnDataSending?.Invoke(this, new SocketEventArgs(data));
}
public virtual void SocketDataReceived(byte[] data)
{
OnDataReceived?.Invoke(this, new SocketEventArgs(data));
}
public virtual void ConnectionLost(Exception ex)
{
OnConnectionLost?.Invoke(this, new SocketEventArgs(ex.Message));
}
#endregion
}
}