-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathHost.cs
95 lines (86 loc) · 2.15 KB
/
Host.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
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
namespace Network
{
public class Host
{
IPEndPoint endPoint;
Thread connectionListener;
bool enabled;
public ArrayList Clients;
public int Backlog = 10;
Socket server;
Type channelType;
object state;
public int BufferSize;
public Host(IPAddress address, int port)
: this(address, port, null)
{
}
public Host(IPAddress address, int port, Type channelType)
: this(address, port, channelType, null)
{
}
public Host(IPAddress address, int port, Type channelType, object state)
{
endPoint = new IPEndPoint(address, port);
this.channelType = channelType;
this.state = state;
Clients = new ArrayList();
}
public void Start()
{
connectionListener = new Thread(new ThreadStart(ConnectionListener));
connectionListener.IsBackground = true;
enabled = true;
connectionListener.Start();
}
public void Stop()
{
enabled = false;
Channel[] c = (Channel[]) Clients.ToArray(typeof(Channel));
for (int i=0; i<c.Length; i++)
c[i].Stop();
connectionListener.Abort();
if (server != null)
{
server.Close();
server = null;
}
}
void ConnectionListener()
{
server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
server.Bind(endPoint);
server.Listen(Backlog);
int id = 0;
while (enabled)
{
Socket socket = server.Accept();
Channel channel;
if (channelType == null)
channel = new Channel();
else
channel = (Channel) channelType.GetConstructor(new Type[] {typeof(object)}).Invoke(new object[] {state});
channel.BufferSize = this.BufferSize;
channel.ConnectFrom(++id, socket);
channel.OnDisconnected += new EventHandler(Disconnected);
Clients.Add(channel);
channel.Start();
channel.Connected();
}
server.Close();
server = null;
}
void Disconnected(object sender, EventArgs e)
{
Channel channel = sender as Channel;
Clients.Remove(channel);
channel.Disconnected();
}
}
}