-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
69 lines (47 loc) · 2.21 KB
/
Copy pathserver.py
File metadata and controls
69 lines (47 loc) · 2.21 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
58
59
60
61
62
63
64
65
66
67
68
69
from socket import gethostbyname, gethostname, socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
import threading, sys
from linked_list import LinkedList
PORT: int = 2781
HOST_IP: str = gethostbyname(gethostname()) # Get IP address of host computer name
ENCODING_DECODING_FORMAT: str = "utf-8"
COMMAND_SIZE: int = 2048 # Server can send and receive a maximum of 2KB of data at a time
NUM_OF_CLIENTS_SERVER_CAN_HANDLE: int = int(sys.argv[1])
client_list: LinkedList = LinkedList()
server: socket = socket(AF_INET, SOCK_STREAM) # Create socket that accepts IPv4 addresses and receives and transmits streams of data
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # Use same address when server is shutdown and restarts again in a short span of time
server.bind((HOST_IP, PORT))
server.listen(NUM_OF_CLIENTS_SERVER_CAN_HANDLE)
print(f"Server listening on port: {PORT}")
def handle_client_connection(conn: socket, client_name: str):
"""
conn: client socket
client_name: client generated username
Facilitates communication between clients.
"""
client_node: LinkedList.Node = LinkedList.Node(client_name, conn)
client_list.insert_node(client_node)
while True:
try:
client_command = conn.recv(COMMAND_SIZE).decode(ENCODING_DECODING_FORMAT)
if client_command and client_command == "exit":
conn.send(client_command.encode(ENCODING_DECODING_FORMAT))
client_list.remove_node(client_name)
break
if client_command:
client_list.broadcast_messages(client_command, client_name)
except Exception as e:
print(e.__str__)
break
conn.close()
def run() -> None:
"""
Runs server for an indefinate period of time.
Accepts a client connection.
Creates a new thread that will be incharge of handling client using handle_client_connection function
"""
while True:
client_conn, _ = server.accept()
client_name = client_conn.recv(COMMAND_SIZE).decode(ENCODING_DECODING_FORMAT) # Receive one time client name
client_thread = threading.Thread(target=handle_client_connection, args=(client_conn, client_name))
client_thread.start()
run()