This blog article shows you how to create a simple TCP listener and client. This code sets up a basic TCP server using Python’s socket module. Here’s a step-by-step explanation:
#1. Import the socket module:
import socket
#2. Create a TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
3. # Bind the socket to a specific address and port
server_socket.bind((‘localhost’, 18999))
4. # Listen for incoming connections
server_socket.listen()
print(“Server is listening on port 18999…”)
try:
while True:
5. # Accept a client connection
client_socket, client_address = server_socket.accept()
print(f”Accepted connection from {client_address[0]}:{client_address[1]}”)
6. # Receive data from the client
data = client_socket.recv(1024)
print(f”Received data: {data.decode()}”)
7. # Send a response back to the client
response = “Hello from the server!”
client_socket.send(response.encode())
8. # Close the client connection
client_socket.close()
except KeyboardInterrupt:
print(“Server stopped by user”)
9. # Close the server socket
server_socket.close()
- while True: Creates an infinite loop to continuously accept connections.
- server_socket.accept(): Waits for an incoming connection. When a client connects, it returns a new socket object (client_socket) and the address of the client (client_address).
- print(f”Accepted connection from {client_address[0]}:{client_address[1]}”): Prints the IP address and port number of the connected client.
Also: Create a Selection Sort in C# using GitHub Copilot
The following script is a simple TCP client that connects to a server, sends a message, and receives a response. Here’s a step-by-step explanation:
# 1. Import the socket module:
import socket
# 2. Define the server’s IP address and port
server_ip = ‘localhost’
server_port = 18999
# 3. Create a TCP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# 4. Connect to the server
client_socket.connect((server_ip, server_port))
# 5. Send the message to the server
message = ‘Hello’
client_socket.sendall(message.encode())
# 6. Receive the response from the server
response = client_socket.recv(1024)
print(‘Response from server:’, response.decode())
finally:
# 7. Close the socket
client_socket.close()
The script follows a typical pattern for TCP client communication: create a socket, connect to a server, send data, receive data, and close the socket.
Source code download: https://github.com/chanmmn/python/tree/main/2024/PythonTCPProgaming?WT.mc_id=DP-MVP-36769
Reference: https://realpython.com/python-sockets/?WT.mc_id=DP-MVP-36769