In this Python Socket Programming article we want to learn about TCP Socket Programming in Python, so TCP (Transmission Control Protocol) is reliable and connection oriented protocol that provides a stream of data between two networked devices. Python provides powerful and easysocket API that allows you to write TCP client and server programs. in this article we want to cover the basics of TCP programming in Python.
Introduction to TCP Socket Programming
Socket programming is a way of connecting two nodes on network to communicate with each other. socket is a software endpoint that establishes communication link between two processes over network. TCP is reliable and connection oriented protocol that establishes connection between two networked devices and provides a stream of data that is guaranteed to be delivered in order and without loss or duplication. Python provides socket API that makes it easy to write TCP client and server programs. socket API is a set of functions and constants that allows you to create, configure and use sockets for network communication.
TCP Socket Programming in Python: A Simple Example
This is simple example of TCP client and server in Python, this is our client code and you can save it in client.py file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Client import socket HOST = 'localhost' PORT = 8000 client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((HOST, PORT)) data = client_socket.recv(1024) print(f"Received data: {data.decode()}") client_socket.close() |
This is our server.py file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Server import socket HOST = 'localhost' PORT = 8000 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((HOST, PORT)) server_socket.listen(1) print(f"Server listening on {HOST}:{PORT}") while True: client_socket, address = server_socket.accept() print(f"Connection from {address} has been established") message = "Welcome to the server" client_socket.send(message.encode()) client_socket.close() |
In this example server listens on port 8000 for incoming connections. hen a client connects, the server sends welcome message to the client and then closes the connection. client connects to the server and receives the welcome message.
To run this code you need to two terminal first run server.py file and after that client.py file
Server in Terminal
Client in Terminal
Learn More
- Python Socket Programming Examples
- Python Socket Programming for Beginners
- Python Socket Server Tutorial
- Python Socket Client Example