-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
57 lines (43 loc) · 1.53 KB
/
server.py
File metadata and controls
57 lines (43 loc) · 1.53 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
#server.py
from socket import *
import threading
# setup the server
port = 8000
s = socket(AF_INET, SOCK_STREAM)
# if not running the program through localhost, please
# switch the port from 8000 to something else as
# port 8000 should not be open to the internet.
s.bind(("localhost", port))
# clients list
clients = []
def listen_to_client(conn, address):
# code for the server to listen and respond to clients
# this function is running in a thread for each client connected
while True:
msg = conn.recv(4096)
# try to see if the message is a quit message,
# if so, respond to the client with a quit message
# to tell it to stop listening
try:
if msg.decode() == "quit":
conn.send(msg)
clients.remove(conn)
break
except:
for client in clients:
client.send(msg)
conn.close()
def get_new_clients(s):
# this function runs in a thread and allows for getting new clients
# upon receiving a new client, that client is added to a clients list
while True:
conn, address = s.accept()
clients.append(conn)
# start a new thread to listen to the new client
threading.Thread(target=listen_to_client, args=(conn, address)).start()
def main():
# server can listen for at most 5 connections, start a new thread that allows for getting clients.
s.listen(5)
threading.Thread(target=get_new_clients, args=(s,)).start()
if __name__ == "__main__":
main()