-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.py
45 lines (34 loc) · 1016 Bytes
/
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
from socket import *
import threading
import json
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(20)
print(f"Server Listening at port [{serverPort}]")
conns = [False for i in range(20)]
def fn(conn, addr, i):
while True:
message = conn.recv(1024)
msg = message.decode()
if msg == 'exit':
conn.send('exit'.encode())
conn.close()
conns[i] = False
return
broadcast(msg.encode())
def broadcast(message):
for i in range(20):
if not conns[i]:
continue
print(f"Sending Message {message} to ")
conns[i].send(message)
while True:
connSocket, addr = serverSocket.accept()
print(f"New Connection created by {addr}")
for i in range(20):
if not conns[i]:
conns[i] = connSocket
break
process = threading.Thread(target=fn, args=[connSocket, addr, i])
process.start()