As you will see in a moment, we will create socket objects using the socket.socket() function and specify the socket type as socket.SOCK_STREAM. When we do this, the default protocol that it uses is the TCP.
For network programming in Python, we need to create a socket object and then use this to call other functions of the module. The following code will start a web server using the sockets library. The script waits for a connection to be made; if it is received, it will show the received bytes.
You can find the following code in the tcp_server.py file:
#!/usr/bin/env python3
import socket
host = '127.0.0.1'
port = 12345
BUFFER_SIZE = 1024
#The socket objects support the context manager type
#so we can use it with a with statement, there's no need to call socket_close ()
#We create a TCP type socket object
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as socket_tcp:
socket_tcp.bind((host, port))
# We wait for the client connection
socket_tcp.listen(5)
# We establish the connection with the client
connection, addr = socket_tcp.accept()
with connection:
print('[*] Established connection')
while True:
# We receive bytes, we convert into str
data = connection.recv(BUFFER_SIZE)
# We verify that we have received data
if not data:
break
else:
print('[*] Data received: {}'.format(data.decode('utf-8')))
connection.send(data)
Let's see what this script does in detail:
- We define the host, the port, and the size of the data buffer that will receive the connection
- We link these variables to our socket object with the socket.bind() method
- We establish the connection, we accept the data, and we visualize the sent data