Creating a TCP client

The following code is an example of a simple TCP client. If you look carefully, you can see that the following code will create a raw HTTP client that fetches a web page from a web server. It sends an HTTP GET request to pull the home page.

To create our connection, we need to import the socket module and use the connect method to pass the (HOST, PORT) tuple as a parameter. With the send method from the socket client object, we send the data for the request and get the response in the data object using the recv method.

You can find the following code in the socket_tcp_client.py file:

import socket

HOST = 'www.yahoo.com'
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 '
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()

This is the output of the socket_tcp_client.py script over the yahoo.com domain for getting information about the server:

In the next section, we are going to study a specific use case with the socket module to obtain information about a server that is running in a specific domain.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset