-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.py
57 lines (41 loc) · 1.28 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
import socket
import threading
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
FORMAT = 'ascii'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((SERVER, PORT))
server.listen()
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def handle_client(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
nicknames.remove(nickname)
break
#receive function
def receive():
while True:
client, addr = server.accept()
print(f"Connected with {str(addr)}")
client.send('WEB'.encode(FORMAT))
nickname = client.recv(1024).decode(FORMAT)
nicknames.append(nickname)
clients.append(client)
print(f"Nickname of the client is {nickname}!")
broadcast(f"{nickname} joined the Chat!".encode(FORMAT))
client.send("Connected to the Server!".encode(FORMAT))
thread = threading.Thread(target = handle_client, args = (client,))
thread.start()
print("[STARTING] Starting the Server...")
receive()