forked from fdorg/flashdevelop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerSocket.cs
More file actions
256 lines (215 loc) · 5.86 KB
/
Copy pathServerSocket.cs
File metadata and controls
256 lines (215 loc) · 5.86 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
253
254
255
256
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
using PluginCore.Managers;
namespace PluginCore.Bridge
{
public class ServerSocket
{
static protected readonly byte[] EOL = new byte[] { 13 };
static protected bool bridgeNotFound;
protected IPAddress ipAddress;
protected int portNum;
protected Socket conn;
protected bool isInvalid;
public event DataReceivedEventHandler DataReceived;
public ServerSocket(String address, Int32 port)
{
if (address == null || address == "invalid")
{
isInvalid = true;
return;
}
try
{
ipAddress = IPAddress.Parse(address);
}
catch (Exception ex)
{
ErrorManager.AddToLog("Invalid IP adress: " + address, ex);
}
portNum = port;
}
public IPAddress IP {
get { return ipAddress; }
}
public int PortNum {
get { return portNum; }
}
#region SERVER
public bool StartServer()
{
try
{
conn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
conn.Bind(new IPEndPoint(ipAddress, portNum));
conn.Listen(10);
conn.BeginAccept(new AsyncCallback(this.OnConnectRequest), conn);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
return true;
}
/// <summary>
/// Accepts the connection request and sets a listener for the next one
/// </summary>
protected void OnConnectRequest(IAsyncResult result)
{
try
{
Socket server = (Socket)result.AsyncState;
Socket client = server.EndAccept(result);
this.SetupReceiveCallback(client);
server.BeginAccept(new AsyncCallback(this.OnConnectRequest), server);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
#endregion
#region CLIENT
public bool ConnectClient()
{
if (bridgeNotFound) return false; // don't fail repeatedly if bridge is not running
try
{
conn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
conn.Connect(new IPEndPoint(ipAddress, portNum));
SetupReceiveCallback(conn);
}
catch (Exception ex)
{
ErrorManager.AddToLog("Failed to connect bridge socket: " + ipAddress + ":" + portNum, ex);
bridgeNotFound = true;
return false;
}
return true;
}
public int Send(string message)
{
return SendTo(conn, message);
}
public void Disconnect()
{
if (conn != null)
{
conn.Disconnect(false);
conn = null;
}
}
#endregion
#region DATA
static public int SendTo(Socket socket, string message)
{
int len = socket.Send(Encoding.UTF8.GetBytes(message));
return len + socket.Send(EOL);
}
/// <summary>
/// Sets up the receive callback for the accepted connection
/// </summary>
protected void SetupReceiveCallback(Socket client)
{
StateObject so = new StateObject(client);
try
{
AsyncCallback receiveData = new AsyncCallback(this.OnReceivedData);
so.Client.BeginReceive(so.Buffer, 0, so.Size, SocketFlags.None, receiveData, so);
}
catch (SocketException)
{
so.Client.Shutdown(SocketShutdown.Both);
so.Client.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// Handles the received data and fires DataReceived event
/// </summary>
protected void OnReceivedData(IAsyncResult result)
{
StateObject so = (StateObject)result.AsyncState;
try
{
Int32 bytesReceived = so.Client.EndReceive(result);
if (bytesReceived > 0)
{
String chunk = Encoding.UTF8.GetString(so.Buffer, 0, bytesReceived);
int star = chunk.IndexOf('*');
if (star >= 0)// .EndsWith("\0"))
{
so.Data.Append(chunk);
string[] lines = so.Data.ToString().Split('*');
foreach (string line in lines)
{
if (line.Length > 0 && this.DataReceived != null)
this.DataReceived(this, new DataReceivedEventArgs(line, so.Client));
}
so.Data = new StringBuilder();
}
else so.Data.Append(chunk);
so.Client.BeginReceive(so.Buffer, 0, so.Size, SocketFlags.None,
new AsyncCallback(this.OnReceivedData), so);
}
else
{
so.Client.Shutdown(SocketShutdown.Both);
so.Client.Close();
}
}
catch (SocketException)
{
so.Client.Shutdown(SocketShutdown.Both);
so.Client.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
#endregion
}
#region STRUCTS
public delegate void DataReceivedEventHandler(Object sender, DataReceivedEventArgs e);
public class DataReceivedEventArgs : EventArgs
{
private String text;
private Socket socket;
public DataReceivedEventArgs(String text, Socket socket)
{
this.text = text;
this.socket = socket;
}
public String Text
{
get { return this.text; }
}
public Socket Socket
{
get { return this.socket; }
}
}
public class StateObject
{
public Int32 Size;
public Socket Client;
public StringBuilder Data;
public Byte[] Buffer;
public StateObject(Socket client)
{
this.Size = 1024;
this.Data = new StringBuilder();
this.Buffer = new Byte[this.Size];
this.Client = client;
}
}
#endregion
}