Socket Programming Tutorial: Building a simple Client-Server setup in Python – By Deepan Gupta
Deepan wrote this tutorial while he was a student at IIIT Hyderabad. After that, he joined Palantir London as a Software Engineer. He currently works at Facebook in Menlo Park.
In the following tutorial we will deal with the basics of socket programming over TCP/IP networks. Also, we will create our own client/server program to create a remote calculator.
This tutorial focuses on socket programming in Python. Those more familiar with Java might find this client-server tutorial more useful.
Sockets are just the endpoints of a two-way communication link in a network. Socket helps in the communication of two processes/programs on a network (eg. Internet).
Bidirectional inter process communication
The programs can communicate by reading/writing via their sockets.
A socket comprises of:
IPv4: 32-bit address
IPv6: 128-bit address
The combination of both is also termed as a socket address. Hence using socket address we can connect to any remote machine.
Every socket follows some protocol (set of rules) for transferring the data. Based on the type of protocol used sockets can be classified as:
Following code shows how to create a socket:
Sockets as we know are used in bidirectional network communication and a good example of it is client/server model. It is architecture for communication between two machines where one requests for information and the other (waiting for requests) generates the desired response.
Client: Client is a machine which generates the requests.
Server: Server is a machine which is generates a response to the corresponding requests. It is always listening for requests.
Consider an example, a website
A website is hosted on a machine (server) which listens continuously for HTTP requests. All the webpages are stored in the server. An webpage is sent as a response to a request.
Normal users who log into the website are actually clients which send HTTP request to access a webpage.
Let’s build an online expression evaluator using client-server architecture. Client will send the expression to the server and the server will give the desired output.
Server will be waiting for the clients to connect and send the expressions. Once a request arrives, it will process the expression and return the desired output back to the client.
Client will initiate a connection to the server. Once the connection is established then client can send the expression to the server as requests.
To stop server Press Ctrl+C
To stop client Press Ctrl+C or Type : quit
Computer Science >