Repository navigation
Expand file tree
/
Copy pathpart2_client (1).py
More file actions
241 lines (207 loc) · 7.62 KB
/
Copy pathpart2_client (1).py
File metadata and controls
241 lines (207 loc) · 7.62 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import argparse
import sys
import socket
import ipaddress
import signal
#main function
# >python3 client.py --id='student1' --port=3000 --server='200.26.180.43:5555'
def sigint_received(signal_received, frame):
sys.stdout.write("\nTerminating the chat client.\nExiting program\n")
sys.stdout.flush()
sys.exit(0)
def register(server_ip, server_port, cl_id, cl_ip, cl_port):
try:
client_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
client_socket.connect((server_ip.strip(), server_port))
except Exception as e:
sys.stdout.write(f"Error: Unable to connect to server. Enter Server first...\n")
sys.stdout.flush()
sys.exit(0)
data = f'REGISTER\r\nclientID: {cl_id}\r\nIP: {cl_ip}\r\nPort: {cl_port}\r\n\r\n'
client_socket.send(data.encode())
regack = client_socket.recv(1024)
client_socket.close()
return regack.decode()
def bridge(server_ip, server_port, cl_id):
try:
client_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
client_socket.connect((server_ip.strip(), server_port))
except Exception as e:
sys.stdout.write(f"Error: Unable to connect to server. Enter Server first...\n")
sys.stdout.flush()
sys.exit(0)
data = f'BRIDGE\r\nclientID: {cl_id}\r\n\r\n'
client_socket.send(data.encode())
bridge_ack= client_socket.recv(1024)
client_socket.close()
return bridge_ack
def check_bridge_chat_ack(ack):
headers = ack.decode().split("\r\n")
headers.pop(len(headers)-1)
headers.pop(len(headers)-1)
headers.pop(0)
field_dict = {}
for field in headers:
header, value = field.split(": ")
field_dict[header] = value
if(field_dict.get("Port") == ''):
return 0, field_dict
else:
return 1, field_dict
def wait(field_dict, cl_port, cl_ip):
client_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
client_socket.bind((cl_ip,cl_port))
client_socket.listen(1)
chat_socket, client_ip_port = client_socket.accept()
info = chat_socket.recv(1024)
code, field_dict = check_bridge_chat_ack(info)
name = field_dict.get("clientID_2")
client_2_ip = field_dict.get("IP_2")
client_2_port = field_dict.get("Port_2")
sys.stdout.write(f"Incoming chat request from {name} {client_2_ip}:{client_2_port}\n")
sys.stdout.flush()
try:
while True:
response = chat_socket.recv(1024)
if response.decode().strip() == "":
break
elif response.decode() == "QUIT\n":
break
sys.stdout.write(response.decode())
sys.stdout.flush()
line = sys.stdin.readline()
if line == "/quit\n":
line= "QUIT\n"
chat_socket.send(line.encode())
break
chat_socket.send(line.encode())
except KeyboardInterrupt:
sys.stdout.write('\n')
sys.stdout.flush()
chat_socket.close()
client_socket.close()
return
def chat(cl_ip, cl_port, cl_id, field_dict):
client_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
client_socket.bind((cl_ip,cl_port))
socket_ip = field_dict.get("IP")
socket_port = int(field_dict.get("Port"))
client_socket.connect((socket_ip, socket_port))
line = f"CHAT\r\nclientID_2: {cl_id}\r\nIP_2: {cl_ip}\r\nPort_2: {cl_port}\r\n\r\n"
client_socket.send(line.encode())
try:
while True:
line = sys.stdin.readline()
if line == "/quit\n":
line= "QUIT\n"
client_socket.send(line.encode())
break
client_socket.send(line.encode())
response = client_socket.recv(1024)
if response.decode().strip() == "":
break
elif response.decode() == "QUIT\n":
break
sys.stdout.write(response.decode())
sys.stdout.flush()
except KeyboardInterrupt:
sys.stdout.write('\n')
sys.stdout.flush()
client_socket.close()
return
"""Socket Start Here"""
def main():
signal.signal(signal.SIGINT, sigint_received)
parse = argparse.ArgumentParser()
parse.add_argument('--id', type=str)
parse.add_argument('--port', type=int)
parse.add_argument('--server', type=str)
args = parse.parse_args()
cl_id = args.id
cl_ip = '127.0.0.1'
try:
cl_port = args.port
if not (1<=cl_port <= 65535):
raise ValueError("Port number must be between 1 and 65535")
except ValueError as e:
sys.stdout.write(f"Error:Invalid port number for Client: {e}\n", file=sys.stderr)
sys.stdout.flush()
sys.exit(1)
try:
server_ip = args.server.split(":")[0]
ipaddress.ip_address(server_ip)
except ValueError:
sys.stdout.write(f"Invalid IP address: {server_ip}\n", file=sys.stderr)
sys.stdout.flush()
sys.exit(1)
try:
server_port = int(args.server.split(":")[1])
if not (1 <= server_port <=65535):
raise ValueError("Port number must be between 1 and 65535.")
except ValueError as e:
sys.stdout.write(f"Error:Invalid port number for Server: {e}\n", file=sys.stderr)
sys.stdout.flush()
sys.exit(1)
sys.stdout.write(f"{cl_id} running on 127.0.0.1:{cl_port}\n")
sys.stdout.flush()
try:
while True:
line = sys.stdin.readline().strip()
if line != "":
if line == '/id':
print(cl_id)
elif line == '/register':
register(server_ip, server_port, cl_id, cl_ip, cl_port)
elif line == '/bridge':
bridge_ack = bridge(server_ip, server_port, cl_id)
size, field_dict = check_bridge_chat_ack(bridge_ack)
if size == 0:
wait(field_dict, cl_port, cl_ip)
break
elif size == 1:
sys.stdout.write('/chat\n')
sys.stdout.flush()
chat(cl_ip, cl_port, cl_id, field_dict)
break
elif line == '/quit':
sys.stdout.write("quitting\n")
sys.stdout.flush()
sys.exit(0)
else:
continue
else:
sys.exit(0)
except KeyboardInterrupt:
sys.stdout.write('Terminating the chat client\n')
sys.stdout.flush()
sys.exit(0)
except EOFError:
sys.stdout.write('Terminating the chat client\n')
sys.stdout.flush()
sys.exit(0)
sys.exit(0)
if __name__ == '__main__':
main()
"""
Citations
- Used help from Chatgpt in implementing the Sigint function
- Used ChatGpt to undertand all the different socket functions and how they work with and
and relate to each other
- Used ChatGpt to understand the process of storing items in a dictionary
"""
"""questions
- what is a valid port and server
- connection correct? when to write client running statement
- when to close
- receive separate function?
- client ip address?
- space after input commands? one quotation or double?
- how to process regack and bridgeack
"""
""" part 2 questions
- how to get client 2 name in client 1? send bridge again?
- okay to send client name to socket first?
- binding okay for client 2
- print /chat manually?
- bind, listen, accept okay? accept only for server?
"""