-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTCP_Chat_Server_Console_rev1.cs.txt
818 lines (682 loc) · 37.7 KB
/
TCP_Chat_Server_Console_rev1.cs.txt
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace TCP_Chat_Server_Console
{
class Program
{
static bool RunProgram = true;
static int worker_TCPServer_count = 4;
static class_mulithreading_Stack shared_worker_TCPServer_status;
static class_worker_TCP_ChatServer[] object_worker_TCP_ChatServer = new class_worker_TCP_ChatServer[worker_TCPServer_count];
static class_Handshake_Passcode[] object_Handshake_Passcode = new class_Handshake_Passcode[worker_TCPServer_count];
static class_currTimeDate currTimeDate = new class_currTimeDate();
static class_check_connection_timeout object_check_connection_timeout = new class_check_connection_timeout(worker_TCPServer_count);
static void Main(string[] args)
{
shared_worker_TCPServer_status = new class_mulithreading_Stack();
Thread[] WorkerThreadsArray_TCP = new Thread[worker_TCPServer_count];
for (int i = 0; i < worker_TCPServer_count; i++)
{
object_Handshake_Passcode[i] = new class_Handshake_Passcode();
object_worker_TCP_ChatServer[i] = new class_worker_TCP_ChatServer(i, 50001 + i);
WorkerThreadsArray_TCP[i] = new Thread(new ThreadStart(object_worker_TCP_ChatServer[i].RunServer));
WorkerThreadsArray_TCP[i].Start();
}
class_portal_TCP_ChatServer object_portal_TCP = new class_portal_TCP_ChatServer();
Thread PortalThread_TCP = new Thread(new ThreadStart(object_portal_TCP.RunServer));
PortalThread_TCP.Start();
Thread Thread_RTC_tick = new Thread(new ThreadStart(currTimeDate.TimerTick));
Thread_RTC_tick.Start();
Thread Thread_check_Connections_Timeout = new Thread(new ThreadStart(object_check_connection_timeout.check_timeout));
Thread_check_Connections_Timeout.Start();
Console.WriteLine("Waiting for connection");
Thread_RTC_tick.Join();
Thread_check_Connections_Timeout.Join();
PortalThread_TCP.Join();
foreach (Thread t in WorkerThreadsArray_TCP)
t.Join();
// Join both threads with no timeout
// Run both until done.
// threads have finished at this point.
}
public class class_mulithreading_Stack
{
private Stack<int> Stack_multithreads;
private int TagNumber;
private bool isLocked;
public class_mulithreading_Stack()
{
isLocked = false;
Stack_multithreads = new Stack<int>();
}
public bool Any()
{
bool _Any;
Monitor.Enter(this); //obtain lock on this object
//if other thread is at present reading / editing this object (isLocked == true), place invoking thread in WaitSleepJoin state
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
try
{
isLocked = true;
_Any = Stack_multithreads.Any();
}
finally
{
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
}
return _Any;
}
public void Push(int theTagNumber)
{
Monitor.Enter(this); //obtain lock on this object
//if other thread is at present reading / editing this object (isLocked == true), place invoking thread in WaitSleepJoin state
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
try
{
isLocked = true;
if(!Stack_multithreads.Contains(theTagNumber)) //make sure duplicate TagNumber does not inserted into the stack
Stack_multithreads.Push(theTagNumber);
}
finally
{
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
}
}
public Tuple<bool, int> Pop()
{
bool Any = false;
Monitor.Enter(this); //obtain lock on this object
//if other thread is at present reading / editing this object (isLocked == true), place invoking thread in WaitSleepJoin state
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
try
{
isLocked = true;
if (Stack_multithreads.Any())
{
TagNumber = Stack_multithreads.Pop();
Any = true;
}
}
finally
{
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
}
//if no data from 'Stack_worker_TCPServer_listening', return false. Else return true.
return new Tuple<bool, int>(Any, TagNumber);
}
}
public class class_currTimeDate
{
//This class "class_currTimeDate" is for simulation purpose only
//Assuming class_currTimeDate is an accurate system clock, TimerTick() is hardware time ticking
private DateTime curr_DateTime;
private bool isLocked;
public class_currTimeDate()
{
curr_DateTime = DateTime.Now;
isLocked = false;
}
public void TimerTick()
{
while (RunProgram)
{
Thread.Sleep(1000);
Monitor.Enter(this); //obtain lock on this object
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
isLocked = true;
curr_DateTime = curr_DateTime.AddSeconds(1);
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
object_check_connection_timeout.notify_timed();
}
}
public DateTime get_curr_DateTime()
{
DateTime _curr_DateTime;
Monitor.Enter(this); //obtain lock on this object
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
isLocked = true;
_curr_DateTime = curr_DateTime;
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
return _curr_DateTime;
}
}
// this class is to generate random handshaking code for chat client to connect to worker chat server
// when new connection, new handshaking code
// if worker chat server received wrong handshake code from chat client, connection will be closed.
public class class_Handshake_Passcode
{
private int Handshake_Passcode;
private bool isLocked;
public class_Handshake_Passcode()
{
isLocked = false;
Random myRandom = new Random();
Handshake_Passcode = myRandom.Next(100);
}
public void set_Handshake_Passcode()
{
Random myRandom = new Random();
Monitor.Enter(this); //obtain lock on this object
//if other thread is at present reading / editing this object (isLocked == true), place invoking thread in WaitSleepJoin state
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
isLocked = true;
Handshake_Passcode = myRandom.Next(100);
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
}
public int get_Handshake_Passcode()
{
int _Handshake_Passcode;
Monitor.Enter(this); //obtain lock on this object
//if other thread is at present reading / editing this object (isLocked == true), place invoking thread in WaitSleepJoin state
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
isLocked = true;
_Handshake_Passcode = Handshake_Passcode;
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
return _Handshake_Passcode;
}
}
class class_check_connection_timeout
{
//This struct will check timeout of waiting pre-assigned clients to connect to worker web servers
struct struct_worker_TCPServer_timeout_WaitConnection
{
private bool isWaitingClientConnection;
private DateTime DateTime_timeout;
public struct_worker_TCPServer_timeout_WaitConnection(bool _isWaitingConnection)
{
isWaitingClientConnection = _isWaitingConnection;
DateTime_timeout = DateTime_Now;
}
public void set_timeout_WaitingClientConnection()
{
isWaitingClientConnection = true;
DateTime_timeout = DateTime_Now.AddSeconds(2);
}
public bool get_timeout_WaitingClientConnection()
{
if (DateTime.Compare(DateTime_Now, DateTime_timeout) > 0)
{
isWaitingClientConnection = false;
return true;
}
return false;
}
public void remove_timeout_WaitingClientConnection()
{
isWaitingClientConnection = false;
}
public bool get_isWaitingClientConnection()
{
return isWaitingClientConnection;
}
}
//This struct will check timeout of clients after they are connected to worker web servers
struct struct_worker_TCPServer_timeout_IdleConnection_TotalConnectedTime
{
private bool isConnected;
private DateTime DateTime_Timeout_IdleConnection;
private DateTime DateTime_Timeout_TotalConnectedTime;
public struct_worker_TCPServer_timeout_IdleConnection_TotalConnectedTime(bool _isConnected)
{
isConnected = _isConnected;
DateTime_Timeout_IdleConnection = DateTime_Now;
DateTime_Timeout_TotalConnectedTime = DateTime_Now;
}
public void set_timeout_IdleConnection(int timeout_period)
{
isConnected = true;
DateTime_Timeout_IdleConnection = DateTime_Now.AddSeconds(timeout_period);
}
public bool get_timeout_IdleConnection()
{
if (DateTime.Compare(DateTime_Now, DateTime_Timeout_IdleConnection) > 0)
{
isConnected = false;
return true;
}
return false;
}
public void set_timeout_TotalConnectedTime(int timeout_period)
{
isConnected = true;
DateTime_Timeout_TotalConnectedTime = DateTime_Now.AddSeconds(timeout_period);
}
public bool get_timeout_TotalConnectedTime()
{
if (DateTime.Compare(DateTime_Now, DateTime_Timeout_TotalConnectedTime) > 0)
{
isConnected = false;
return true;
}
return false;
}
public void remove_isConnected()
{
isConnected = false;
}
public bool get_isConnected()
{
return isConnected;
}
}
private bool isLocked;
private bool is_RTC_interrupt;
private static DateTime DateTime_Now;
private struct_worker_TCPServer_timeout_IdleConnection_TotalConnectedTime[] worker_TCPServer_timeout_IdleConnection_TotalConnectedTime;
private struct_worker_TCPServer_timeout_WaitConnection[] worker_TCPServer_timeout_WaitingClientConnection;
private int Worker_TCPServer_count;
public class_check_connection_timeout(int _worker_TCPServer_count)
{
isLocked = false;
is_RTC_interrupt = false;
DateTime_Now = DateTime.Now;
Worker_TCPServer_count = _worker_TCPServer_count;
worker_TCPServer_timeout_IdleConnection_TotalConnectedTime = new struct_worker_TCPServer_timeout_IdleConnection_TotalConnectedTime[Worker_TCPServer_count];
worker_TCPServer_timeout_WaitingClientConnection = new struct_worker_TCPServer_timeout_WaitConnection[Worker_TCPServer_count];
for (int i = 0; i < Worker_TCPServer_count; i++)
{
worker_TCPServer_timeout_IdleConnection_TotalConnectedTime[i] = new struct_worker_TCPServer_timeout_IdleConnection_TotalConnectedTime(false);
worker_TCPServer_timeout_WaitingClientConnection[i] = new struct_worker_TCPServer_timeout_WaitConnection(false);
}
}
public void notify_timed()
{
Monitor.Enter(this); //obtain lock on this object
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
isLocked = true;
DateTime_Now = DateTime.Now;
is_RTC_interrupt = true;
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
}
public void check_timeout()
{
Monitor.Enter(this); //obtain lock on this object
while (RunProgram)
{
if (!is_RTC_interrupt)
Monitor.Wait(this);
//if other thread is at present reading / editing this object (isLocked == true), place invoking thread in WaitSleepJoin state
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
isLocked = true;
try
{
if (is_RTC_interrupt)
{
for (int i = 0; i < Worker_TCPServer_count; i++)
{
if (worker_TCPServer_timeout_WaitingClientConnection[i].get_isWaitingClientConnection())
{
if (worker_TCPServer_timeout_WaitingClientConnection[i].get_timeout_WaitingClientConnection()) // if current port number timeout in waiting for expected client to connect
{
object_Handshake_Passcode[i].set_Handshake_Passcode();
shared_worker_TCPServer_status.Push(i);
}
}
else
{
if (worker_TCPServer_timeout_IdleConnection_TotalConnectedTime[i].get_isConnected())
{
if (worker_TCPServer_timeout_IdleConnection_TotalConnectedTime[i].get_timeout_IdleConnection()) // if current port number client connection idle too long, timeout
{
worker_TCPServer_timeout_IdleConnection_TotalConnectedTime[i].remove_isConnected();
object_worker_TCP_ChatServer[i].close_connection("IDLE TIMEOUT");
}
else
{
if (worker_TCPServer_timeout_IdleConnection_TotalConnectedTime[i].get_timeout_TotalConnectedTime()) // if current port number client total connected time too long, timeout
{
worker_TCPServer_timeout_IdleConnection_TotalConnectedTime[i].remove_isConnected();
object_worker_TCP_ChatServer[i].close_connection("TOTAL TIME TIMEOUT");
}
}
}
}
}
is_RTC_interrupt = false;
}
}
finally
{
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
}
}
Monitor.Exit(this); //release lock on this object
}
public void set_timeout_WaitingConnection(int workerTCPserverID)
{
Monitor.Enter(this); //obtain lock on this object
//if other thread is at present reading / editing this object (isLocked == true), place invoking thread in WaitSleepJoin state
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
isLocked = true;
try
{
worker_TCPServer_timeout_WaitingClientConnection[workerTCPserverID].set_timeout_WaitingClientConnection();
}
finally
{
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
}
}
public void remove_WaitingConnections(int workerTCPserverID)
{
Monitor.Enter(this); //obtain lock on this object
//if other thread is at present reading / editing this object (isLocked == true), place invoking thread in WaitSleepJoin state
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
isLocked = true;
try
{
worker_TCPServer_timeout_WaitingClientConnection[workerTCPserverID].remove_timeout_WaitingClientConnection();
}
finally
{
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
}
}
public void set_timeout_IdleConnection(int workerTCPserverID, int timeout_period)
{
Monitor.Enter(this); //obtain lock on this object
//if other thread is at present reading / editing this object (isLocked == true), place invoking thread in WaitSleepJoin state
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
isLocked = true;
try
{
worker_TCPServer_timeout_IdleConnection_TotalConnectedTime[workerTCPserverID].set_timeout_IdleConnection(timeout_period);
}
finally
{
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
}
}
public void set_timeout_TotalConnectedTime(int workerTCPserverID, int timeout_period)
{
Monitor.Enter(this); //obtain lock on this object
//if other thread is at present reading / editing this object (isLocked == true), place invoking thread in WaitSleepJoin state
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
isLocked = true;
try
{
worker_TCPServer_timeout_IdleConnection_TotalConnectedTime[workerTCPserverID].set_timeout_TotalConnectedTime(timeout_period);
}
finally
{
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
}
}
public void remove_isConnected(int workerTCPserverID)
{
Monitor.Enter(this); //obtain lock on this object
//if other thread is at present reading / editing this object (isLocked == true), place invoking thread in WaitSleepJoin state
if (isLocked)
Monitor.Wait(this); //enter WaitSleepJoin state
isLocked = true;
try
{
worker_TCPServer_timeout_IdleConnection_TotalConnectedTime[workerTCPserverID].remove_isConnected();
}
finally
{
isLocked = false;
Monitor.Pulse(this); //tell waiting thread(if there is one) to become ready to execute (Running state)
Monitor.Exit(this); //release lock on this object
}
}
}
public class class_worker_TCP_ChatServer
{
private Socket connection; // Socket for accepting a connection
private NetworkStream socketStream; // network data stream
private BinaryWriter writer; // facilitates writing to the stream
private BinaryReader reader; // facilitates reading from the stream
private TcpListener listener;
public int port_number;
public int HandshakePasscode;
private int worker_TCP_ChatServer_ID;
public class_worker_TCP_ChatServer(int ID, int portNumber)
{
// Step 1: create TcpListener
IPAddress local = IPAddress.Parse("127.0.0.1");
listener = new TcpListener(local, portNumber);
port_number = portNumber;
HandshakePasscode = 0; //Should generate random Handshake Code.
worker_TCP_ChatServer_ID = ID;
}
// allow a client to connect; displays text the client sends
public void RunServer()
{
while (RunProgram)
{
// wait for a client connection and display the text that the client sends
try
{
// Step 2: TcpListener waits for connection request
listener.Start();
// Step 3: establish connection upon client request
// accept an incoming connection
connection = listener.AcceptSocket();
// create NetworkStream object associated with socket
socketStream = new NetworkStream(connection);
// create objects for transferring data across stream
writer = new BinaryWriter(socketStream);
reader = new BinaryReader(socketStream);
object_check_connection_timeout.remove_WaitingConnections(worker_TCP_ChatServer_ID);
IPEndPoint ep = connection.RemoteEndPoint as IPEndPoint;
if (ep != null)
Console.WriteLine("worker port " + port_number + " connected to client wih IP " + ep.Address.ToString());
string theReply = "";
HandshakePasscode = object_Handshake_Passcode[worker_TCP_ChatServer_ID].get_Handshake_Passcode();
// read handshaking passcode sent from client to worker server. Client must send handshake passcode to server within 1 second, or else worker server will close this connection.
object_check_connection_timeout.set_timeout_IdleConnection(worker_TCP_ChatServer_ID, 1);
theReply = reader.ReadString();
// If HandshakeCode sent by TCP client tally with worker TCP server.
if (theReply == ("<CLIENT><HandshakePasscode>" + HandshakePasscode + "</HandshakePasscode></CLIENT>"))
{
// inform client that connection was successful
writer.Write("<SERVER type='worker' port='" + port_number + "'><message>Connection successful</message></SERVER>");
if (ep != null)
Console.WriteLine("worker port " + port_number + " handshake with client IP " + ep.Address.ToString() + " successful.");
// Worker server only allows client to be continously connected to worker server for 10 mins. After 10 mins, worker server disconnects the client even client is active in communication.
object_check_connection_timeout.set_timeout_TotalConnectedTime(worker_TCP_ChatServer_ID, 600);
// Step 4: read string data sent from client
do
{
try
{
// client if idle more than 1 minute and not sending data to worker server, worker server close the connection.
object_check_connection_timeout.set_timeout_IdleConnection(worker_TCP_ChatServer_ID, 60);
// read the string sent to the server
theReply = reader.ReadString();
// display the message
Console.WriteLine("\r\n" + theReply);
// this code section is for simulation purpose only.
// simulate one chat client chating with another chat client
if (theReply != "<CLIENT><command>TERMINATE</command></CLIENT>")
{
if (port_number == 50001)
object_worker_TCP_ChatServer[1].server_send_text(theReply);
if (port_number == 50002)
object_worker_TCP_ChatServer[0].server_send_text(theReply);
if (port_number == 50003)
object_worker_TCP_ChatServer[3].server_send_text(theReply);
if (port_number == 50004)
object_worker_TCP_ChatServer[2].server_send_text(theReply);
}
// end of simulation
}
catch (Exception)
{
// handle exception if error reading data
break;
}
} while (theReply != "<CLIENT><command>TERMINATE</command></CLIENT>" && theReply != "<CLIENT><command>IDLE TIMEOUT</command></CLIENT>" && theReply != "<CLIENT><command>TOTAL TIME TIMEOUT</command></CLIENT>" && connection.Connected);
}
else
{
// If TCP client's handshake passcode does not tally with worker TCP server. Or client sending other irrelevant info but not handshake passcode.
//client only has one chance sends the correct handshake passcode.
if (theReply != "")
server_send_text("<SERVER type='worker' port='" + port_number + "'><message>Wrong handshake passcode</message></SERVER>");
}
if (theReply == "<CLIENT><command>TERMINATE</command></CLIENT>")
Console.WriteLine("\r\nUser terminated connection on port " + port_number);
if (theReply == "<CLIENT><command>IDLE TIMEOUT</command></CLIENT>")
Console.WriteLine("\r\nClient close connection due to idle timeout on port " + port_number);
if (theReply == "<CLIENT><command>TOTAL TIME TIMEOUT</command></CLIENT>")
Console.WriteLine("\r\nClient close connection due to total time timeout on port " + port_number);
}
catch (Exception error)
{
Console.WriteLine(error.ToString());
Thread.Sleep(100);
}
finally
{
// Step 5: close connection
writer.Close();
reader.Close();
socketStream.Close();
connection.Close();
object_Handshake_Passcode[port_number - 50001].set_Handshake_Passcode(); // Worker server change to new handshake passcode whenever closing the current connection.
object_check_connection_timeout.remove_isConnected(worker_TCP_ChatServer_ID);
shared_worker_TCPServer_status.Push(port_number); //This worker TCP server is available to receive new incoming TCP client connection.
}
}
}
public void server_send_text(string SendText)
{
if(connection != null && connection.Connected)
writer.Write(SendText);
}
public void close_connection(string message_to_client)
{
if (connection != null && connection.Connected)
writer.Write("<SERVER><command>" + message_to_client + "</command></SERVER>");
writer.Close();
reader.Close();
socketStream.Close();
connection.Close();
Console.WriteLine("\r\nWorker Server port " + port_number + " disconnected due to " + message_to_client);
}
}
public class class_portal_TCP_ChatServer
{
private Socket connection; // Socket for accepting a connection
private NetworkStream socketStream; // network data stream
private BinaryWriter writer; // facilitates writing to the stream
private BinaryReader reader; // facilitates reading from the stream
private TcpListener listener;
public int port_number;
public class_portal_TCP_ChatServer()
{
// Step 1: create TcpListener
IPAddress local = IPAddress.Parse("127.0.0.1");
listener = new TcpListener(local, 50000);
port_number = 50000;
for (int i = 0; i < worker_TCPServer_count; i++)
shared_worker_TCPServer_status.Push(i + 50001);
}
// allow a client to connect; displays text the client sends
public void RunServer()
{
while (RunProgram)
{
// wait for a client connection and display the text that the client sends
try
{
// Step 2: TcpListener waits for connection request
listener.Start();
// Step 3: establish connection upon client request
// accept an incoming connection
connection = listener.AcceptSocket();
// create NetworkStream object associated with socket
socketStream = new NetworkStream(connection);
// create objects for transferring data across stream
writer = new BinaryWriter(socketStream);
reader = new BinaryReader(socketStream);
// inform client to switch-over from master_TCP connection to idle worker_TCP connection
if (shared_worker_TCPServer_status.Any())
{
Tuple<bool, int> worker_TCP_port = shared_worker_TCPServer_status.Pop();
if (worker_TCP_port.Item1)
{
object_check_connection_timeout.set_timeout_WaitingConnection(worker_TCP_port.Item2 - 50001);
writer.Write("<SERVER type='worker'><Port>" + worker_TCP_port.Item2 + "</Port><HandshakePasscode>" + object_Handshake_Passcode[worker_TCP_port.Item2 - 50001].get_Handshake_Passcode() + "</HandshakePasscode></SERVER>");
//Console.WriteLine("\r\nAssigned to port " + worker_TCP_port.Item2);
}
else
writer.Write("<SERVER><command>FULL</command></SERVER>");
}
else
writer.Write("<SERVER><command>FULL</command></SERVER>");
// Step 5: close connection
writer.Close();
reader.Close();
socketStream.Close();
connection.Close();
}
catch (Exception error)
{
Console.WriteLine(error.ToString());
Thread.Sleep(100);
}
}
}
public void server_send_text(string SendText)
{
if(connection.Connected)
writer.Write(SendText);
}
public void close_connection()
{
writer.Close();
reader.Close();
socketStream.Close();
connection.Close();
}
}
}
}