← Go Back
Now, to create a TCP connection we need two files: one for the server and one for the client. The server must create a socket object and indicate that it will listen for requests on a given IP address (local or public) and port.
Once the server is running, we must create and run the client. We are using the
Both points of the connection can send and receive data via the
See also our article on sending files through a socket.
How to Create a TCP Client/Server Connection
Thesocket
standard module provides a low-level interface for creating TCP and UDP connections. To create servers with a higher level interface, see the standard socketserver module. For medium and large projects, consider more complete solutions such as Twisted.Now, to create a TCP connection we need two files: one for the server and one for the client. The server must create a socket object and indicate that it will listen for requests on a given IP address (local or public) and port.
# server.py
from socket import socket
# Create the socket.
with socket() as s:
# Associate it with an IP address and a port.
s.bind(("localhost", 6190))
# Indicate that this socket will act as a server.
s.listen()
# Wait for the client to connect.
print("Waiting for client...")
conn, address = s.accept()
print(f"{address[0]}:{address[1]} has connected.")
# Wait for the client to send data.
while True:
data = conn.recv(1024)
# Check that it is not empty.
if data:
# Print received data and close the socket.
print("The client sent:", data)
break
# The socket is automatically closed upon exiting the "with" block.
print("Connection closed.")
Once the server is running, we must create and run the client. We are using the
create_connection()
function to connect to the server and send data over the connection.# client.py
from socket import create_connection
# Connect to the server.
with create_connection(("localhost", 6190)) as conn:
print("Connected to server.")
# Send data.
conn.sendall(b"Hello world!")
print("Connection closed.")
Both points of the connection can send and receive data via the
sendall()
and recv(n)
methods (where n
indicates the size of the buffer in bytes, usually 1024).See also our article on sending files through a socket.
🐍 You might also find interesting: