forked from kazenif/ImacocoNow_Taxi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TcpServerTaxi.cs
350 lines (298 loc) · 10.7 KB
/
TcpServerTaxi.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace PCGPS
{
/// <summary>
/// TCP サーバのメッセージを受け取るイベント用デリゲート
/// </summary>
/// <param name="message"></param>
//public delegate void TcpServerEvent(string message);
/// <summary>
/// TCP サーバ
/// </summary>
class TcpServerTaxi
{
/// <summary>
/// 待ち受けポート
/// </summary>
const int Port = 3201;
/// <summary>
/// TCP 待ち受けオブジェクト
/// </summary>
TcpListener tcpListener;
/// <summary>
/// 接続してきたクライアントの情報
/// </summary>
List<ClientContext> clients;
/// <summary>
/// 待ち受けスレッド
/// ブロッキングモードで動作するので、
/// 別スレッドで起動
/// </summary>
Thread listenerThread;
/// <summary>
/// サーバ停止フラグ
/// </summary>
bool StopFlag;
/// <summary>
/// メッセージ通知用デリゲート
/// </summary>
TcpServerEvent tcpServerEvent;
// --------------------------------------------------------------------
/// <summary>
/// コンストラクタ
/// </summary>
public TcpServerTaxi()
{
tcpListener = null;
clients = new List<ClientContext>();
StopFlag = false;
listenerThread = null;
tcpServerEvent = null;
}
/// <summary>
/// TCP サーバのメッセージを受け取るイベントハンドラの登録
/// </summary>
/// <param name="method"></param>
public void RegisterTcpServerEvent(TcpServerEvent method)
{
tcpServerEvent = method;
}
/// <summary>
/// サーバ停止
/// </summary>
public void Stop()
{
StopFlag = true;
// クラアントとの接続を全て閉じる
foreach (ClientContext context in clients)
{
context.tcpClient.Close();
context.StopFlag = true;
context.thread.Join();
}
// 待ち受けを停止する
if (tcpListener != null)
tcpListener.Stop();
// 待ち受けスレッドを停止する
if (listenerThread != null)
{
listenerThread.Join();
listenerThread = null;
}
invokeServerEvent("サーバが停止されました。");
}
/// <summary>
/// サーバ開始
/// </summary>
public void Start()
{
if (listenerThread != null)
return;
StopFlag = false;
// サーバ待ち受けスレッドを開始する
listenerThread = new Thread(new ThreadStart(Listen));
listenerThread.Start();
invokeServerEvent("サーバが開始されました。");
}
/// <summary>
/// サーバのメッセージを伝えるイベントを呼び出す
/// </summary>
/// <param name="message"></param>
private void invokeServerEvent(string message)
{
if (tcpServerEvent != null)
tcpServerEvent(message);
}
/// <summary>
/// クライアントを切断する
/// </summary>
/// <param name="context"></param>
private void CloseClient(ClientContext context)
{
clients.Remove(context);
//invokeServerEvent("クライアントの接続を閉じました。 : " + context.tcpClient.Client.RemoteEndPoint.ToString());
invokeServerEvent("クライアントの接続を閉じました。");
invokeServerEvent("現在の接続数: " + clients.Count);
}
/// <summary>
/// データ受信
/// </summary>
/// <param name="context"></param>
/// <param name="stream"></param>
private void ReadStream(ClientContext context, NetworkStream stream)
{
BinaryReader reader = new BinaryReader(stream);
// 受信タイムアウト時間の設定
stream.ReadTimeout = 1000;
// ブロッキングモードでデータを受信
while (stream.DataAvailable)
{
try
{
byte type = reader.ReadByte();
switch (type)
{
case 2:
int size = reader.ReadInt32();
byte[] byteArray = reader.ReadBytes(size);
string str = Encoding.UTF8.GetString(byteArray);
if (context.tcpClient.Client.Connected == false)
break;
string message = context.tcpClient.Client.RemoteEndPoint.ToString() + " : " + str;
invokeServerEvent(message);
SendMessageAll(message);
break;
}
}
catch (EndOfStreamException)
{
invokeServerEvent("ReadStream() で例外が発生しました。クライアントを切断します。");
context.StopFlag = true;
CloseClient(context);
break;
}
catch (IOException)
{
// タイムアウト
invokeServerEvent("ReadStream() で例外が発生しました。クライアントを切断します。");
context.StopFlag = true;
CloseClient(context);
break;
}
}
}
/// <summary>
/// クライアントからのデータを待つループ
/// </summary>
/// <param name="param"></param>
private void ClientLoop(Object param)
{
ClientContext context = (ClientContext)param;
TcpClient client = context.tcpClient;
int loopCount = 0;
if (client.Connected == false)
return;
NetworkStream stream = client.GetStream();
while (!context.StopFlag)
{
loopCount++;
// 接続チェック
//if (loopCount > 100)
//{
// loopCount = 0;
// BinaryWriter writer = new BinaryWriter(stream);
// try {
// byte packetType = 0;
// writer.Write(packetType);
// }
// catch (IOException)
// {
// invokeServerEvent("ClientLoop() で例外が発生しました。クライアントを切断します。");
// CloseClient(context);
// break;
// }
//}
if (!client.Client.Connected)
{
CloseClient(context);
break;
}
if (stream.DataAvailable)
{
ReadStream(context, stream);
}
// 10 ミリ秒待つ
Thread.Sleep(10);
}
client.Close();
}
/// <summary>
/// クライアントに文字列のメッセージを送信する
/// </summary>
/// <param name="stream"></param>
/// <param name="message"></param>
private void SendMessage(ClientContext context, string message)
{
Stream stream = context.tcpClient.GetStream();
BinaryWriter writer = new BinaryWriter(stream);
byte[] byteArray = Encoding.UTF8.GetBytes(message);
try
{
writer.Write(byteArray.Length);
writer.Write(byteArray);
writer.Flush();
}
catch (IOException)
{
invokeServerEvent("SendMessage() で例外が発生しました。クライアントを切断します。");
CloseClient(context);
}
}
/// <summary>
/// 全てのクライアントに文字列のメッセージを送信する
/// </summary>
/// <param name="message"></param>
public void SendMessageAll(string message)
{
if (clients != null)
{
try
{
foreach (ClientContext context in clients)
{
SendMessage(context, message);
}
}
catch (Exception)
{
}
}
}
/// <summary>
/// サーバ待ち受けループ
/// </summary>
private void Listen()
{
tcpListener = new TcpListener(IPAddress.Any, Port);
tcpListener.Start();
invokeServerEvent("接続を待っています。");
while (!StopFlag)
{
if (tcpListener.Pending())
{
try
{
Thread thread = new Thread(new ParameterizedThreadStart(ClientLoop));
TcpClient client = tcpListener.AcceptTcpClient();
ClientContext context = new ClientContext(client, thread);
clients.Add(context);
if (context.tcpClient.Connected == false)
{
CloseClient(context);
continue;
}
//SendMessage(context, "サーバからのメッセージ : 接続しました");
thread.Start(context);
invokeServerEvent("クライアントが接続しました。 : " + client.Client.RemoteEndPoint.ToString());
invokeServerEvent("現在の接続数: " + clients.Count);
}
catch (SocketException e)
{
invokeServerEvent("エラー (SocketException) : " + e.ToString());
continue;
}
}
Thread.Sleep(10);
}
tcpListener.Stop();
}
}
}