-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
98 lines (79 loc) · 2.98 KB
/
server.py
File metadata and controls
98 lines (79 loc) · 2.98 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
93
94
95
96
97
import threading
import socket
host = "127.0.0.1"
port = 55555
admin_password = input("Please enter the password of the admin: ")
server = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
msg = message = client.recv(1024)
if msg.decode("ascii").startswith("KICK"):
if nicknames[clients.index(client)] == "admin":
name_to_kick = msg.decode("ascii")[5:]
kick_user(name_to_kick)
else:
client.send("You do not have permission!".encode("acii"))
elif msg.decode("ascii").startswith("BAN"):
if nicknames[clients.index(client)] == "admin":
name_to_ban = msg.decode("ascii")[4:]
kick_user(name_to_ban)
with open("bans.txt", "a") as f:
f.write(f"{name_to_ban}\n")
print(f"{name_to_ban} was banned!")
else:
client.send("You do not have permission!".encode("acii"))
else:
broadcast(message)
except:
if client in clients:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast(f"{nickname} left the chat!".encode("ascii"))
nicknames.remove(nickname)
break
def receive():
while True:
client, address = server.accept()
print(f"Connected with {str(address)}")
client.send("NICK".encode("ascii"))
nickname = client.recv(1024).decode("ascii")
with open("bans.txt", "r") as f:
bans = f.readlines()
if nickname+"\n" in bans:
client.send("BAN".encode("ascii"))
client.close()
continue
if nickname == "admin":
client.send("PASS".encode("ascii"))
password = client.recv(1024).decode("ascii")
if password != admin_password:
client.send("REFUSE".encode("ascii"))
client.close()
continue
nicknames.append(nickname)
clients.append(client)
print(f"Nickname of the client is {nickname}!")
broadcast(f"{nickname} joined the chat!".encode("ascii"))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
def kick_user(name):
if name in nicknames:
name_index = nicknames.index(name)
client_to_kick = clients[name_index]
clients.remove(client_to_kick)
client_to_kick.send("You have been kicked!".encode("ascii"))
client_to_kick.close()
nicknames.remove(name)
broadcast(f"{name} was kicked!".encode("ascii"))
print(f"Server started on {port}!")
receive()