-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.cs
188 lines (150 loc) · 5.8 KB
/
Server.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
using System;
using System.Net;
using System.IO;
using System.Threading;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class Server
{
static public void Main ()
{
IDictionary<string, TcpClient> clients = new Dictionary<string, TcpClient>();
// Choose port
Console.WriteLine("Please enter port number to start server at (default: 8888)");
string portInput = Console.ReadLine();
int port = int.TryParse(portInput, out port) ? port : 8888;
// Create and start server
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener server = new TcpListener(ip, port);
try {
server.Start();
Console.WriteLine(String.Format("[Server]: Started at port {0}", port));
}
catch (SocketException exception) {
string error = exception.Message;
Console.WriteLine(String.Format("Could not start server: {0}", error));
return;
}
// Chat loop
while (true) {
// Some delay is ok
Thread.Sleep(100);
// Check if we have pending connections
if (server.Pending()) {
// Connect to the client
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("[Handshake]: New client connected");
// Settle username with client
string response;
do {
// Receive name from client
string username;
NetworkStream stream;
try {
stream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int data = stream.Read(buffer, 0, client.ReceiveBufferSize);
username = Encoding.Unicode.GetString(buffer, 0, data);
Console.WriteLine(String.Format("[Handshake]: Requesting username '{0}' ", username));
}
catch (IOException exception) {
string error = exception.Message;
Console.WriteLine(String.Format("[Handshake]: Did not receive username from new conncetion ({0})", error));
break;
}
// Validate username
bool isOk = String.IsNullOrEmpty(username) ? false : true;
// Uniqueness
foreach (var user in clients) {
if (user.Key == username) {
isOk = false;
}
}
// Length
if (username.Length > 10) {
isOk = false;
}
if (isOk) {
Console.WriteLine(String.Format("[Handshake]: Granting username '{0}' ", username));
clients.Add(username, client);
// Print all current users
Console.WriteLine("===MEMBERS===");
foreach(var c in clients) {
Console.WriteLine(c.Key);
}
Console.WriteLine("=============");
} else {
Console.WriteLine(String.Format("[Handshake]: Rejecting username '{0}' ", username));
}
// Send username response
try {
response = isOk ? "ACCEPT" : "REJECT";
byte[] message = Encoding.Unicode.GetBytes(response);
stream.Write(message, 0, message.Length);
} catch (IOException exception) {
string error = exception.Message;
Console.WriteLine(String.Format("[Handshake]: Could not send message back to client that requested {0} ({1})", username, error));
break;
}
} while (response != "ACCEPT");
}
// Remove disconnected clients
bool hadStaleClients = clients.Any(c => !c.Value.Connected);
foreach(var client in clients.Where(c => !c.Value.Connected).ToList()) {
Console.WriteLine(String.Format("[Remove]: [{0}]", client.Key));
}
clients = clients.Where(c => c.Value.Connected)
.ToDictionary(c => c.Key, c => c.Value);
if (hadStaleClients) {
Console.WriteLine("===MEMBERS===");
foreach(var c in clients) {
Console.WriteLine(c.Key);
}
Console.WriteLine("=============");
}
// Check if new messages have arrived
foreach(var sender in clients) {
string senderName = sender.Key;
TcpClient senderClient = sender.Value;
NetworkStream senderStream = senderClient.GetStream();
// Is there a new message?
if (senderStream.DataAvailable) {
string text;
try {
// Read the message
byte[] buffer = new byte[senderClient.ReceiveBufferSize];
int data = senderStream.Read(buffer, 0, senderClient.ReceiveBufferSize);
text = Encoding.Unicode.GetString(buffer, 0, data);
}
catch (SocketException exception) {
string error = exception.Message;
Console.WriteLine(String.Format("[ERROR]: Could not read message from [{0}]", senderName));
continue;
}
// Display message
Console.WriteLine(String.Format("[Broadcast]: {0}", text));
// Broadcast to all other clients
foreach(var receiver in clients) {
string receiverName = receiver.Key;
if (receiverName != senderName) {
TcpClient receiverClient = receiver.Value;
Console.WriteLine(String.Format("[Send] from [{0}] to [{1}]", senderName, receiverName));
try {
NetworkStream receiverStream = receiverClient.GetStream();
byte[] message = Encoding.Unicode.GetBytes(text);
receiverStream.Write(message, 0, message.Length);
} catch (IOException exception) {
string error = exception.Message;
Console.WriteLine(String.Format("[ERROR]: Broadcast from [{0}] to [{1}] failed.", senderName, receiverName));
}
}
}
}
}
// Close connection to client
//client.Close();
}
}
}