-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackListener.cs
More file actions
92 lines (77 loc) · 2.34 KB
/
Copy pathStackListener.cs
File metadata and controls
92 lines (77 loc) · 2.34 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
using NetworkingStack.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace NetworkingStack.Server
{
public class StackListener
{
private static readonly int sendBufferSize = 64 * 1024;
private static readonly int receiveBufferSize = 64 * 1024;
private Socket server;
public bool Listening { get; private set; }
public void Listen(ushort port)
{
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, port);
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
{
SendBufferSize = sendBufferSize,
ReceiveBufferSize = receiveBufferSize,
};
server.Bind(ipEndPoint);
server.Listen(500);
server.BeginAccept(Process, null);
Listening = true;
}
private void Process(IAsyncResult r)
{
try
{
new StackClient(this, server.EndAccept(r));
}
catch (Exception ex)
{
OnServerException(ex);
}
finally
{
server.BeginAccept(Process, null);
}
}
public event ExceptionHandler ServerException;
public event StatusChangedHandler ClientStatusChanged;
public event ExceptionHandler ClientException;
public event ReadBufferHandler ClientReadData;
internal void OnClientReadData(object sender, byte[] buffer)
{
if (ClientReadData != null)
{
ClientReadData(sender, buffer);
}
}
internal void OnClientException(object sender, Exception ex)
{
if (ClientException != null)
{
ClientException(sender, ex);
}
}
internal void OnClientStatusChanged(object sender, int status)
{
if (ClientStatusChanged != null)
{
ClientStatusChanged(sender, status);
}
}
internal void OnServerException(Exception ex)
{
if(ServerException != null)
{
ServerException(this, ex);
}
}
}
}