-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient.py
More file actions
68 lines (56 loc) · 1.92 KB
/
Copy pathclient.py
File metadata and controls
68 lines (56 loc) · 1.92 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
import socket
import threading
SERVER_ADDRESS = ('127.0.0.1', 15662)
ENCODING = 'utf-8'
def handle_server_instruction(message):
# expected interaction
if message == '%NICK%':
client_socket.send(nickname.encode(ENCODING))
elif message == '%PASS%':
password = input('Password required: ')
client_socket.send(password.encode(ENCODING))
# expected termination
elif message == '%BANNED%':
print('You are currently banned')
client_socket.close()
exit(1)
elif message == '%DUPLICATE%':
print('This nickname is already taken, please reconnect with another one')
client_socket.close()
exit(1)
elif message == '%QUIT%':
print('Exiting...')
client_socket.close()
exit(0)
else:
print(f'Received unknown instruction "{message}" from server')
def receive():
"""Pool messages from server (runs in separate thread)"""
while True:
try:
message = client_socket.recv(1024).decode(ENCODING)
if message.startswith('%'):
handle_server_instruction(message)
else:
print(message)
except OSError:
print('An error occurred!')
client_socket.close()
break
def write():
"""Hold open input for sending messages (runs in separate thread)"""
while True:
message = f'{input("")}'
client_socket.send(message.encode(ENCODING))
if __name__ == '__main__':
try:
nickname = input("Choose a nickname: ")
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(SERVER_ADDRESS)
except ConnectionRefusedError:
print('Could not connect to the server. Exiting...')
exit(1)
receive_threat = threading.Thread(target=receive)
receive_threat.start()
write_thread = threading.Thread(target=write)
write_thread.start()