-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.py
95 lines (84 loc) · 3.39 KB
/
server.py
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
import socket
import threading
host = '127.0.0.1'
port = 55555
# to start server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
def broadcast_msg(message):
for client in clients:
client.send(message)
def manage(client):
while True:
try:
message = client.recv(1024).decode('ascii')
if message.startswith('KICK'):
if nicknames[clients.index(client)]=='admin' :
name_to_kick=message[5:]
kick_user(name_to_kick)
else:
client.send('Command was refused!'.encode('ascii'))
elif message.startswith('BAN'):
if nicknames[clients.index(client)] == 'admin' :
name_to_ban=message[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 from the server')
else:
client.send('Command was refused!'.encode('ascii'))
else:
message2=message.encode('ascii')
broadcast_msg(message2)
except: # on exception
if client in clients:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast_msg(
f'{nickname} has left the chat.'.encode('ascii'))
print("Client has left the chat with nickname ", nickname)
nicknames.remove(nickname)
break
def receive():
while True:
client, address = server.accept()
print(f'New Client is connected with the Address = {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 != 'adminpass':
client.send('Incorrect'.encode('ascii'))
client.close()
continue
nicknames.append(nickname)
clients.append(client)
print(f'Client\'s nickname : {nickname}')
broadcast_msg(f'{nickname} has just joined the chat !'.encode('ascii'))
client.send(f'Successfully Connected to Server '.encode('ascii'))
thread = threading.Thread(target=manage, 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 were kicked '.encode('ascii'))
client_to_kick.close()
nicknames.remove(name)
broadcast_msg(f'{name} was kicked by an admin'.encode('ascii'))
print("-----------------------------server is running-------------------------")
receive()