-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.py
More file actions
70 lines (58 loc) · 1.77 KB
/
Copy pathClient.py
File metadata and controls
70 lines (58 loc) · 1.77 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
import json
import socket
import re
import threading
HEADER = 128
PORT = 7070
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "DISCONNECT"
SERVER = "192.168.21.1"
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
# Function to handle sending messages
def send_message():
while True:
msg = input()
if msg == DISCONNECT_MESSAGE:
send(msg)
print("Disconnected from server!!")
client.close()
break
else:
send(msg)
# Function to handle receiving messages
def receive_message():
while True:
try:
message = client.recv(2048).decode(FORMAT)
if message:
try:
response = json.loads(message)
print(
f"Server:\n{response}----------------------------------------------------\nYour next "
f"request?...\n")
except json.JSONDecodeError:
print(message)
else:
print("Disconnected from server.")
break
except ConnectionResetError:
print("Server connection was closed.")
break
# Helper function to format and send messages
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
# Starting threads for reading and writing
receive_thread = threading.Thread(target=receive_message)
send_thread = threading.Thread(target=send_message)
receive_thread.start()
send_thread.start()
# Wait for threads to complete before exiting
receive_thread.join()
send_thread.join()