Chapter 7
Enter the target host name to connect:
http://www.asgdfdfdkflakslalalasdsdsds.invalid
Enter the target port: 80
Failed to connect to http://www.asgdfdfdkflakslalalasdsdsds.invalid on port
80
Reason: [Errno -2] Name or service not known
Now, let's exchange some data with the server. The following code is an example of a
simple TCP client:
import socket
HOST = 'www.linux.org' # or 'localhost'
PORT = 80
BUFSIZ = 4096
ADDR = (HOST, PORT)
if __name__ == '__main__':
client_sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
client_sock.connect(ADDR)
while True:
data = 'GET / HTTP/1.0\r\n\r\n'
if not data:
break
client_sock.send(data.encode('utf-8'))
data = client_sock.recv(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))
client_sock.close()
If you look carefully, you can see that the preceding code actually created a raw
HTTP client that fetches a web page from a web server. It sends an HTTP GET
request to pull the home page:
python 7_2_simple_tcp_client.py
HTTP/1.1 200 OK
Date: Sat, 07 Mar 2015 16:23:02 GMT
Server: Apache
Last-Modified: Mon, 17 Feb 2014 03:19:34 GMT
Accept-Ranges: bytes