-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathserver.py
More file actions
58 lines (41 loc) · 1.38 KB
/
server.py
File metadata and controls
58 lines (41 loc) · 1.38 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
import socket
import threading
host = '127.0.0.1'
port = 55555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
print(f"Server running on {host}:{port}")
clients = []
usernames = []
def broadcast(message, _client):
for client in clients:
if client != _client:
client.send(message)
def handle_messages(client):
while True:
try:
message = client.recv(1024)
broadcast(message, client)
except:
index = clients.index(client)
username = usernames[index]
broadcast(f"ChatBot: {username} disconnected".encode('utf-8'), client)
clients.remove(client)
usernames.remove(username)
client.close()
break
def receive_connections():
while True:
client, address = server.accept()
client.send("@username".encode("utf-8"))
username = client.recv(1024).decode('utf-8')
clients.append(client)
usernames.append(username)
print(f"{username} is connected with {str(address)}")
message = f"ChatBot: {username} joined the chat!".encode("utf-8")
broadcast(message, client)
client.send("Connected to server".encode("utf-8"))
thread = threading.Thread(target=handle_messages, args=(client,))
thread.start()
receive_connections()