forked from BinniesLite/networking_final_project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
58 lines (47 loc) · 1.47 KB
/
client.py
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
import socket
import threading
def receive_messages():
global running
while running:
try:
message = client.recv(1024).decode('utf-8')
if message.startswith("exit"):
running = False
break
print(message)
except Exception as e:
print(f'An error occurred: {e}')
break
def send_messages():
global running
while running:
try:
command = input()
client.send(command.encode('utf-8'))
except Exception as e:
print(f'Exiting the group chat {e}')
break
if __name__ == "__main__":
running = True
s = ""
while True:
s = input("Use command '%connect [address] [port]' to connect to the server\n")
if not s.startswith("%connect"):
print("invalid inputs")
continue
else:
break
s = s.split(" ")
host, port = s[1], int(s[2])
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
# Start receiving messages in a separate thread
receive_thread = threading.Thread(target=receive_messages)
receive_thread.start()
# Start sending messages in a separate thread
send_thread = threading.Thread(target=send_messages)
send_thread.start()
# Join threads to ensure proper exit
receive_thread.join()
send_thread.join()
client.close()