forked from pcewebpython/echo-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
echo_client.py
65 lines (51 loc) · 1.61 KB
/
echo_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
59
60
61
62
63
64
65
"""
The client program
"""
import socket
import sys
import traceback
SERVER = 'localhost'
PORT = 10000
def client(msg, log_buffer=sys.stderr):
""" The client function """
server_address = (SERVER, PORT)
data_chunk = 16
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP)
sock.settimeout(2)
print('connecting to {0} port {1}'.format(*server_address),
file=log_buffer)
sock.connect(server_address)
# entire message
received_message = ''
# this try/finally block exists purely to allow us to close the socket
# when we are finished with it
try:
print('sending "{0}"'.format(msg), file=log_buffer)
sock.sendall(msg.encode('utf-8'))
while True:
chunk = sock.recv(data_chunk)
received_message += chunk.decode('ascii')
print('received "{0}" len {1}'.format(chunk.decode('utf8'),
len(chunk)),
file=log_buffer)
if not chunk:
break
except socket.timeout:
print('message end')
except socket.error:
traceback.print_exc()
print("Exception {}".format(sys.exc_info()[0]))
sys.exit(1)
finally:
sock.close()
print('closing socket', file=log_buffer)
return received_message
if __name__ == '__main__':
if len(sys.argv) != 2:
USAGE = '\nusage: python echo_client.py "this is my message"\n'
print(USAGE, file=sys.stderr)
sys.exit(1)
MSG = sys.argv[1]
client(MSG)