Starting a client

We are going to write a program that defines a client that opens the connection in a given port and host. This is very simple to do with the socket.connect (hostname, port) function, which opens a TCP connection to the hostname on the port. Once we have opened an object socket, we can read and write this in as any other object of input and output (I/O), always remembering to close it as we close files after working with them.

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

#!/usr/bin/env python3

import socket

# The client must have the same server specifications
host = '127.0.0.1'
port = 12345
BUFFER_SIZE = 1024

MESSAGE = 'Hello world,this is my first message'

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_tcp:
socket_tcp.connect((host, port))
# We convert str to bytes
socket_tcp.send(MESSAGE.encode('utf-8'))
data = socket_tcp.recv(BUFFER_SIZE)

This script is similar to the previous one, only this time, we define a MESSAGE variable that simulates the data packets, we make the connection like we did before, and call the socket.send(data) method after converting our string into bytes to ensure the integrity of our data.

To execute this pair of sample scripts, we must first execute the server with the following command:

$ python tcp_server.py &

We append the ampersand, &, so that this line is executed and the process is open and waiting for another command (when pressing Enter, the server will be executed until we execute the client), and then we initiate the client:

$ python tcp_client.py

The result in the server part is as follows:

$ python tcp_server.py
[*] Established connection
[*] Data received: Hello world,this is my first message
..................Content has been hidden....................

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