-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
46 lines (36 loc) · 990 Bytes
/
server.py
File metadata and controls
46 lines (36 loc) · 990 Bytes
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
import socket
import threading
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostbyname(socket.gethostname()), 1111))
s.listen(8)
clients = []
# broadcast message
def broadcast(message):
for client in clients:
client.send(message)
# handle client
def handle(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
clients.remove(client)
client.close()
break
# receive clients
def receive():
while True:
# accept connection
client, adress = s.accept()
print(f"{adress} joined chat")
# inform client
clients.append(client)
client.send("Connected to server \n".encode())
# broadcast to all clients
broadcast("\nAnother fag joined the chat!\n".encode())
# create handle thread
h_thread = threading.Thread(target=handle, args=(client,))
h_thread.start()
print("Server is listening...")
receive()