-
-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathclient.py
More file actions
64 lines (39 loc) · 1.35 KB
/
Copy pathclient.py
File metadata and controls
64 lines (39 loc) · 1.35 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
#!/usr/bin/env python3
#
# https://docs.python.org/3.5/library/socket.html
#
import socket
# --- constants ---
HOST = '' # (local or external) address IP of remote server
PORT = 8000 # (local or external) port of remote server
# server can have local address IP - used only in local network
# or external address IP - used in internet on external router
# (and router redirects data to internal address IP)
# --- create socket ---
print('[DEBUG] create socket')
#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = socket.socket() # default value is (socket.AF_INET, socket.SOCK_STREAM)
# so you don't have to use it in socket()
# --- connect to server ---
print('[DEBUG] connect:', HOST, PORT)
s.connect((HOST, PORT)) # one tuple (HOST, PORT), not two arguments
# --- send data ---
# if you don't use native characters
# then you can use 'ascii' instead of 'utf-8'
print('[DEBUG] send')
text = "Hello World of Sockets in Python"
data = text.encode('utf-8') # encode string to bytes
s.send(data)
print(text)
# --- receive data ---
# if you don't use native characters
# then you can use 'ascii' instead of 'utf-8'
print('[DEBUG] receive')
data = s.recv(1024)
text = data.decode('utf-8') # decode bytes to string
print(text)
# --- close socket ---
print('[DEBUG] close socket')
import time
input("[ENTER]: ")
s.close()