-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathTcpServer.cs
107 lines (92 loc) · 3.38 KB
/
TcpServer.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EasyPipes
{
/// <summary>
/// A <see cref="TcpListener"/> based IPC server
/// </summary>
public class TcpServer : Server
{
/// <summary>
/// IP and address bound by the server
/// </summary>
public IPEndPoint EndPoint { get; private set; }
/// <summary>
/// Encryption algorithm
/// </summary>
protected Encryptor Encryptor { get; private set; }
/// <summary>
/// The Tcp connection
/// </summary>
protected TcpListener listener;
/// <summary>
/// Construct the server
/// </summary>
/// <param name="address">Address and port to bind for the server</param>
/// <param name="encryptor">Optional encryption algorithm for the messages, will be enabled
/// after call to an <see cref="EncryptIfTrueAttribute"/> labeled method</param>
public TcpServer(IPEndPoint address, Encryptor encryptor = null) : base(null)
{
EndPoint = address;
Encryptor = encryptor;
}
/// <summary>
/// Start listening on the TCP socket
/// </summary>
protected override void DoStart()
{
listener = new TcpListener(EndPoint);
listener.ExclusiveAddressUse = false;
listener.Start();
Task t = Task.Factory.StartNew(ReceiveAction);
serverTask.Add(t);
}
/// <summary>
/// Stop listening on the TCP socket
/// </summary>
public override void Stop()
{
base.Stop();
listener.Stop();
}
/// <summary>
/// Main connection loop, waits for and handles connections
/// </summary>
protected override void ReceiveAction()
{
try
{
var t = listener.AcceptTcpClientAsync(CancellationToken.Token);
// wait for connection
using (System.Net.Sockets.TcpClient client = t.GetAwaiter().GetResult())
{
// Start new connection waiter before anything can go wrong here,
// leaving us without a server
serverTask.Add(Task.Factory.StartNew(ReceiveAction));
using (NetworkStream networkStream = client.GetStream())
{
networkStream.ReadTimeout = Server.ReadTimeOut;
Stream serverStream = networkStream;
Guid id = Guid.NewGuid();
IpcStream stream = new IpcStream(serverStream, KnownTypes, Encryptor);
// process incoming messages until disconnect
while (ProcessMessage(stream, id))
{ }
StatefulProxy.NotifyDisconnect(id);
serverStream.Close();
}
}
}
catch (OperationCanceledException) { }
}
}
}