-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_server.py
48 lines (32 loc) · 1.18 KB
/
tcp_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
import threading, socket, datetime, time
text_type = "utf-8"
host = "0.0.0.0"
port = 7000
prefix = str(datetime.date.today()) + " " + str(time.strftime("%H:%M:%S", time.localtime()))
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((host,port))
server.listen(5)
clients = []
def broadcast(msg):
for i in clients:
message = msg.encode(text_type)
i.send(message)
def get_message(client_reference):
while True:
try:
message = client_reference.recv(1024).decode(text_type)
broadcast(message)
except:
index = clients.index(client_reference)
clients.remove(client_reference)
client_reference.close()
break
def new_client():
while True:
client_reference,client_info = server.accept()
print("[" + str(datetime.date.today()) + " " + str(time.strftime("%H:%M:%S", time.localtime())) +f"] Connected with {client_info[0]}")
clients.append(client_reference)
client_reference.send(str("ready").encode(text_type))
thread = threading.Thread(target=get_message, args=[client_reference])
thread.start()
new_client()