-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
53 lines (41 loc) · 1.3 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
import argparse
import socket
import struct
import sys
def encode_data(data: str) -> bytes:
'''
Encode data with the following format:
b"< 4 bytes describing the length of the data in little-endian >< The data >"
'''
data_length = struct.pack("<I", len(data))
encoded_data = data_length + data.encode()
return encoded_data
def send_data(server_ip: str, server_port: int, data: str):
'''
Send data to server in address (server_ip, server_port).
'''
sock = socket.socket()
sock.connect((server_ip, server_port))
sock.sendall(encode_data(data))
def get_args():
parser = argparse.ArgumentParser(description='Send data to server.')
parser.add_argument('server_ip', type=str,
help='the server\'s ip')
parser.add_argument('server_port', type=int,
help='the server\'s port')
parser.add_argument('data', type=str,
help='the data')
return parser.parse_args()
def main():
'''
Implementation of CLI and sending data to server.
'''
args = get_args()
try:
send_data(args.server_ip, args.server_port, args.data)
print('Done.')
except Exception as error:
print(f'ERROR: {error}')
return 1
if __name__ == '__main__':
sys.exit(main())