-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.d
100 lines (75 loc) · 1.78 KB
/
listener.d
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
import std.stdio : writeln;
import std.socket;
import std.conv;
import std.algorithm : remove;
import std.getopt;
struct Sender {
string name;
Socket sock;
this(string name, Socket sock) {
this.name = name;
this.sock = sock;
}
}
bool getString(Socket sock, out string output) {
char[1024] buf;
auto dataLength = sock.receive(buf);
if(dataLength != 0) {
output = to!(string)(buf[0..dataLength]);
return true;
}
else if(dataLength == Socket.ERROR)
writeln("Connection error");
else {
writeln("Connection closed");
}
output = "";
return false;
}
void main(string[] args) {
ushort listenedPort = 2015;
auto result = getopt(args,
"p", "port", &listenedPort);
if(result.helpWanted) {
defaultGetoptPrinter("Some info about the program.", result.options);
}
auto listenerSocket = new TcpSocket();
listenerSocket.bind(new InternetAddress(listenedPort));
listenerSocket.listen(0);
enum MaxConnection = 60;
auto sendersSet = new SocketSet(MaxConnection + 1);
Sender[] senders;
for(;;) {
sendersSet.add(listenerSocket);
foreach(sender; senders) {
sendersSet.add(sender.sock);
}
Socket.select(sendersSet, null, null);
foreach(i, sender; senders) {
if(sendersSet.isSet(sender.sock)) {
string buffer;
if(sender.sock.getString(buffer)){
writeln("by ", sender.name, ": ");
writeln(buffer);
continue;
}
sender.sock.close();
senders = senders.remove(i);
i--;
}
}
if(sendersSet.isSet(listenerSocket)) {
Socket newSenderSocket = listenerSocket.accept();
string name;
if(newSenderSocket.getString(name)) {
writeln("New connection: ", name);
Sender sender = Sender(name, newSenderSocket);
senders ~= sender;
}
}
sendersSet.reset();
}
scope(exit) {
listenerSocket.close();
}
}