-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cs
More file actions
85 lines (71 loc) · 2.58 KB
/
server.cs
File metadata and controls
85 lines (71 loc) · 2.58 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
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class ChatRoomServer {
private Dictionary<Socket, string> clients = new Dictionary<Socket, string>();
private const int bufferSize = 1024;
private const int port = 8888;
public void Start() {
TcpListener serverSocket = new TcpListener(IPAddress.Any, port);
serverSocket.Start();
Console.WriteLine("Server started.");
while (true) {
Socket clientSocket = serverSocket.AcceptSocket();
string username = ReceiveUsername(clientSocket);
clients.Add(clientSocket, username);
SendMessageToAllClients(username + " has joined.");
Thread clientThread = new Thread(HandleClient);
clientThread.Start(clientSocket);
}
}
private string ReceiveUsername(Socket clientSocket) {
byte[] buffer = new byte[bufferSize];
int bytesRead = clientSocket.Receive(buffer);
return Encoding.ASCII.GetString(buffer, 0, bytesRead);
}
private void HandleClient(object clientSocket) {
Socket client = (Socket)clientSocket;
string username = clients[client];
Console.WriteLine("Client connected: " + username);
while (true) {
try {
byte[] buffer = new byte[bufferSize];
int bytesRead = client.Receive(buffer);
string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
if (message.ToLower() == "exit") {
SendMessageToAllClients(username + " has left.");
clients.Remove(client);
break;
}
if (message.ToLower().Contains("placeholder")) {
message = message.Replace("placeholder", "[CENSORED]");
}
Console.WriteLine("Received from client: " + message);
SendMessageToAllClients(message);
}
catch (Exception ex) {
Console.WriteLine("Error: " + ex.Message);
clients.Remove(client);
client.Close();
break;
}
}
}
private void SendMessageToAllClients(string message)
{
foreach (Socket client in clients.Keys)
{
byte[] buffer = Encoding.ASCII.GetBytes(message);
client.Send(buffer);
}
}
}
class Program {
static void Main(string[] args) {
ChatRoomServer server = new ChatRoomServer();
server.Start();
}
}