forked from furas/python-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
67 lines (42 loc) · 1.3 KB
/
Copy pathclient.py
File metadata and controls
67 lines (42 loc) · 1.3 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
#!/usr/bin/env python3
import struct
import socket
import sys
# --- constants ---
HOST = '' # (local or external) address IP of remote server
PORT = 8000 # (local or external) port of remote server
try:
# --- create socket ---
print('[DEBUG] create socket')
#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = socket.socket() # default: socket.AF_INET, socket.SOCK_STREAM
# --- connect to server ---
print('[DEBUG] connect:', (HOST, PORT))
s.connect((HOST, PORT)) # one tuple (HOST, PORT), not two arguments
# --- send data ---
print('[DEBUG] send')
text = 'Hello World of Sockets in Python'
print('[DEBUG] text:', text)
# convert text to bytes
data = text.encode('utf-8')
print('[DEBUG] data:', data)
# get data length
length = len(data)
print('[DEBUG] length:', length)
# convert `length` int to 4 bytes
length = struct.pack('!i', length)
print('[DEBUG] length as 4 bytes:', length)
# send `length` as 4 bytes
s.send(length)
# send data as bytes
s.send(data)
except Exception as ex:
print(ex)
except KeyboardInterrupt as ex:
print(ex)
except:
print(sys.exc_info())
finally:
# --- close socket ---
print('[DEBUG] close socket')
s.close()