-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
57 lines (50 loc) · 1.46 KB
/
client.py
File metadata and controls
57 lines (50 loc) · 1.46 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
import threading, socket
class Client:
def receive(self, client: socket.socket):
while True:
try:
message = client.recv(1024).decode()
if message == 'nickname':
client.send(nickname.encode())
if message == 'Server is out!':
print(message)
client.close()
break
else:
print(message)
except:
print('An error occurred!')
client.close()
break
def write(self, client: socket.socket):
while True:
try:
message = f'{nickname}: {input("")}'
client.send(len(message).to_bytes(4, byteorder='big'))
client.send(message.encode())
except:
print('An error occurred!')
client.close()
break
if __name__ == '__main__':
host = '127.0.0.1'
port = 55555
nickname = input("Choose a nickname: ")
threads_list = []
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
client_class = Client()
receive_thread = threading.Thread(target=client_class.receive, args=(client,))
receive_thread.daemon = True
threads_list.append(receive_thread)
receive_thread.start()
write_thread = threading.Thread(target=client_class.write, args=(client,))
write_thread.daemon = True
threads_list.append(write_thread)
write_thread.start()
for thr in threads_list:
thr.join()
except:
print("Closing client!")
client.close()