-
Notifications
You must be signed in to change notification settings - Fork 557
/
ClientHandlerThread.cs
executable file
·120 lines (102 loc) · 3.04 KB
/
ClientHandlerThread.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
#nullable enable
using System.Net.Sockets;
using System.Threading;
using System;
using QuickFix.Logger;
namespace QuickFix
{
/// <summary>
/// Created by a ThreadedSocketReactor to handle a client connection.
/// Each ClientHandlerThread has a SocketReader which reads
/// from the socket.
/// </summary>
internal class ClientHandlerThread : IResponder, IDisposable
{
internal class ExitedEventArgs : EventArgs
{
public ClientHandlerThread ClientHandlerThread { get; private set; }
public ExitedEventArgs(ClientHandlerThread clientHandlerThread)
{
ClientHandlerThread = clientHandlerThread;
}
}
internal delegate void ExitedEventHandler(object sender, ClientHandlerThread.ExitedEventArgs e);
internal event ExitedEventHandler? Exited;
public long Id { get; private set; }
private Thread? _thread = null;
private volatile bool _isShutdownRequested = false;
private readonly SocketReader _socketReader;
internal ClientHandlerThread(
TcpClient tcpClient,
long clientId,
SocketSettings socketSettings,
AcceptorSocketDescriptor? acceptorDescriptor,
NonSessionLog nonSessionLog
) {
Id = clientId;
_socketReader = new SocketReader(tcpClient, socketSettings, this, acceptorDescriptor, nonSessionLog);
}
public void Start()
{
_thread = new Thread(Run);
_thread.Start();
}
public void Shutdown(string reason)
{
// TODO - need the reason param?
_isShutdownRequested = true;
}
public void Join()
{
if (_thread is null)
return;
if (_thread.IsAlive)
_thread.Join(5000);
_thread = null;
}
private void Run()
{
while (!_isShutdownRequested)
{
try
{
_socketReader.Read();
}
catch (Exception e)
{
Shutdown(e.Message);
}
}
OnExited();
}
private void OnExited() {
Exited?.Invoke(this, new ExitedEventArgs(this));
}
#region Responder Members
public bool Send(string data)
{
return _socketReader.Send(data) > 0;
}
public void Disconnect()
{
Shutdown("Disconnected");
}
#endregion
~ClientHandlerThread() => Dispose(false);
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
_socketReader.Dispose();
}
_disposed = true;
}
}
}