-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
118 lines (91 loc) · 4.07 KB
/
Copy pathserver.py
File metadata and controls
118 lines (91 loc) · 4.07 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import socket
import sys
import argparse
import select
import re
clients = {}
active_clients = []
def parse_input():
parser = argparse.ArgumentParser(description="Chat server program")
parser.add_argument("--port", required=True, help="server port")
args = parser.parse_args()
if len(sys.argv) < 2:
print("Usage: python3 p2-sptjohns-erwalee-server.py --port <port>")
sys.exit(1)
# test args here
try:
args.port = int(args.port)
except ValueError:
print("Error: arguments incorrect")
exit(1)
return args
def register_user(lines, s_ip, s_port, c_socket):
nothing, nothing, c_id = str(lines[1]).partition(":") # reading message
c_id = c_id.strip()
nothing, nothing, c_ip = str(lines[2]).partition(":")
c_ip = c_ip.strip()
nothing, nothing, c_port = str(lines[3]).partition(":")
c_port = c_port.strip()
clients[c_id] = f"{c_ip}:{c_port}" # parsing message
print(f"REGISTER: {c_id} from {c_ip}:{c_port} received")
# sending REGACK
msg = f"REGACK\r\nclientID: {c_id}\r\nIP: {s_ip}\r\nPort: {s_port}\r\nStatus: registered\r\n\r\n"
c_socket.send(msg.encode())
def bridge_user(lines, c_socket):
# reading message sent
nothing, nothing, c_id = str(lines[1]).partition(":")
c_id = c_id.strip()
active_clients.append(c_id) # adding to the list of active clients
# if one client, send empty bridgeack, if multiple bridge incoming with exisiting
if (len(active_clients) == 1):
print(f"BRIDGE: {c_id} {clients[c_id].partition(':')[0]}:{clients[c_id].partition(':')[2]}")
msg = f"BRIDGEACK\r\nclientID: \r\nIP: \r\nPort: \r\n\r\n"
c_socket.send(msg.encode())
elif (len(clients) > 1):
print(f"BRIDGE: {active_clients[0]} {clients[active_clients[0]].partition(':')[0]}:{clients[active_clients[0]].partition(':')[2]} {c_id} {clients[c_id].partition(':')[0]}:{clients[c_id].partition(':')[2]}")
msg = f"BRIDGEACK\r\nclientID: {active_clients[0]}\r\nIP: {clients[active_clients[0]].partition(':')[0]}\r\nPort: {clients[active_clients[0]].partition(':')[2]}\r\n\r\n"
c_socket.send(msg.encode())
def main():
args = parse_input()
s_port = args.port
s_ip = "127.0.0.1"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# make sure this ip is correct
s.bind((s_ip, s_port))
data = s.getsockname()
print(f">Server running on {data[0]}:{data[1]}")
s.listen()
while(True):
ready_to_read, _, _ = select.select([s, sys.stdin], [], [], 1.0)
for sock in ready_to_read:
if sock is s:
(c_socket, c_ip) = s.accept() # accepting connections
c_data = c_socket.recv(1024) # reading data
#print(c_data.decode())
c_data = c_data.decode()
#print(c_data)
lines = c_data.splitlines() # splitting message
#print(lines)
if (lines[0] == 'REGISTER'): # choosing register or bridge
register_user(lines, s_ip, s_port, c_socket)
elif (lines[0] == 'BRIDGE'):
bridge_user(lines, c_socket)
else:
print("Malformed incoming message", file=sys.stderr) # fix to stderr
# need to properly close silly goose
c_socket.close()
s.close()
sys.exit(1) # better for exiting bc of error
c_data = None
elif sock is sys.stdin:
user_input = sys.stdin.readline().strip() # getting user input
if (user_input == "/info"):
for client in clients.keys():
print(f"{client} {clients[client]}")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nTerminating server")
exit()