This article is participating in Python Theme Month. See the link to the event for more details

In today’s tutorial, we’ll cover the basics of Python’s Socket programming. Python’s socket interface is similar to C and Java. Therefore, learning socket programming in Python is much easier if you already have a C/Java programming background.

But using sockets in Python is much simpler, which encourages rapid application development. So instead of worrying about whether Python is your first programming language, feel lucky.

Python provides two types of API libraries that can be used for socket programming. At the bottom level, Python uses the “socket” library to implement client and server modules for connectionless and connection-oriented network protocols. At a higher level, you can use libraries such as FTplib and Httplib to interact with application-level network protocols such as FTP and HTTP.

In this article, we’ll discuss the most widely used “socket” library specifically designed for Python socket programming. We’ll look at the main features provided by the library that can help you build client and server modules. Finally, you’ll see a demonstration of client-server communication with sample code.

Sockets are the most important and basic entity to learn about in Python socket programming. In this section, we introduced the concept of sockets and the methods associated with creating and communicating with them.

Python Socket programming brief

What is a socket?

A socket is the endpoint of a two-way communication link. An endpoint is a combination of an IP address and a port number.

For client-server communication, you need to configure sockets on both ends to initiate connections, listen for incoming messages, and then send responses on both ends to establish two-way communication.

Sockets allow communication between processes that reside on the same machine, or between processes that work on different machines in different environments, or even across different continents.

How to create a Socket object in Python?

To create/initialize a socket, we use the socket.socket() method. It is defined in the Socket module in Python. The syntax is as follows.

sock_obj = socket.socket(socket_family, socket_type, protocol=0)
Copy the code

Where is it,

  • Socket_family: Defines the protocol family used as the transport mechanism. It can have either of two values.

    • AF_UNIX, or
    • AF_INET (IP version 4 or IPv4).
  • Socket_type: Defines the communication type between two endpoints. It can have the following values.

    • SOCK_STREAM (for connection-oriented protocols such as TCP), or
    • SOCK_DGRAM (for connectionless protocols such as UDP).
  • Protocol: We usually leave this field or set this field to zero.

import socket   #for sockets

# Instantiate an AF_INET, STREAM socket (TCP)

sock_obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print ('Socket Initialized')
Copy the code

That’s how you create a socket object. But what if the above example fails to instantiate the socket. How will you resolve the error?

You need to wrap the above code in Python’s try and except blocks. With Python exception handling, you can trace the cause of the error.

Error in managing Python socket programming
 
import socket   #for sockets
import sys  #for exit
 
try:
    # Create AF_INET, STREAM socket (TCP)

    sock_obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err_msg:
    print ('Unable to instantiate socket. Error code: ' + str(err_msg[0]) + ' , Error message : ' + err_msg[1])
    sys.exit();
 
print ('Socket Initialized')
Copy the code

In the following sections, we will explain the functions available in the Socket library to create client/server programs.

How many socket methods are available in Python’s socket library?

We can divide the socket methods for Python socket programming into three categories.

  • Server socket method,
  • Client socket method, and
  • Generic socket methods.

What are the methods available for server sockets?

Server socket method

  • sock_object.bind

    • This method binds the socket to the address (host name, port number pair)
  • Sock_object. Listen (backlog) :

    • This method is used to listen for connections associated with a socket.
    • The backlog parameter indicates the maximum number of queued connections.
    • The maximum can be 5, and the minimum should be at least zero.
  • sock_object.accept():

    • This function returns a (conn, address) pair, where “CONN” is the new socket object used to send and receive data on the communication channel, and “address” is the IP address bound to the socket at the other end of the channel.
    • The ACCEPT() method returns a socket object that is different from the socket object created using socket.socket().
    • This new socket object is designed to manage communication with the particular client where the acceptance occurs.
    • This mechanism also helps the server stay connected to n clients simultaneously.

What are the methods available for client sockets?

Client socket method

  • sock_object.connect():

    • This method is used to connect the client to the host and port and start the connection to the server.

What are the generic socket methods available in Python?

Generic socket methods

  • sock_object.recv():

    • Use this method to receive messages at the endpoint when the value of the protocol parameter is TCP.
  • sock_object.send():

    • If the protocol is TCP, this method is applied to send messages from the endpoint.
  • sock_object.recvfrom():

    • If the protocol used is UDP, this method is called to receive messages at the endpoint.
  • sock_object.sendto():

    • If the protocol parameter is UDP, this method is called to send messages from the endpoint.
  • sock_object.gethostname():

    • This method returns the host name.
  • sock_object.close():

    • This method is used to close the socket. The remote endpoint does not receive data from this end.

So far, we’ve listed all the socket tools the “Socket” library provides for Python socket programming. Next, we’ll show you the socket function call workflow that implements client-server communication. Refer to the following snapshot. It describes each socket call required to establish a channel between the client and server.

Python Socket programming workflow

The following figure depicts the order in which socket methods are called on the client and server endpoints.

So, from the flowchart above, you’ll see all the socket methods needed to create a client/server socket program in Python. Now it’s time to set up the real Python client and server components.

Sample code for Python client-server communication

The client-server program will have the following two Python modules.

  • Python – Server. Py and
  • Python – Client. Py.

Let’s examine the server code first. Note that we have already tested this code on Python 3.

Python-Server.py

The server module will send and receive data to/from the client.

  • The python-server. py file contains the code to create the Server socket that waits until a request is received from the client.

  • Whenever a client connects, the server accepts the connection.

    • The client will then start delivering messages to the server.
    • The server processes the messages and sends the response back to the client.
  • In the code below, we also ask the user to enter the response he wants to pass to the client.

import socket
import time

def Main() :
    host = "127.0.0.1"
    port = 5001

    mySocket = socket.socket()
    mySocket.bind((host,port))
                
    mySocket.listen(1)
    conn, addr = mySocket.accept()
    print ("Connection from: " + str(addr))

    while True:
        data = conn.recv(1024).decode()
        if not data:
            break
        print ("from connected user: " + str(data))
                                                
        data = str(data).upper()
        print ("Received from User: " + str(data))

        data = input("? ")
        conn.send(data.encode())
                                                
    conn.close()
                
if __name__ == '__main__':
    Main()
Copy the code

Python-Client.py

On the client side, we create a socket and connect to the server using the host and port values provided.

  • The client code has a while loop that is used to exchange messages. It keeps printing all the data it gets from the server.
  • After that, theThe inputFunction to request a client response. The response is then passed to the server.
  • The user can also enter “Q” at any point in time to stop communication.
import socket

def Main() :
    host = '127.0.0.1'
    port = 5001

    mySocket = socket.socket()
    mySocket.connect((host,port))

    message = input("? ")

    whilemessage ! ='q':
        mySocket.send(message.encode())
	data = mySocket.recv(1024).decode()

	print ('Received from server: ' + data)
	message = input("? ")

    mySocket.close()

if __name__ == '__main__':
    Main()
Copy the code

How do I run a client-server program?

You need to run both modules from separate command Windows, or you can run them in two different IDLE instances.

First, you’ll execute the server module, then the client. We have given a complete execution summary of the client-server program.

Python 3.51. (v3. 51.:37a07cee5969, Dec  6 201501:54:25) [MSC v1900. 64 bit (AMD64)] on win32
Type "copyright"."credits" or "license()" for more information.

 RESTART: C:\Users\Techbeamers\AppData\Local\Programs\Python\Python35\Python-Server.py 
Connection from: ('127.0.0.1'.50001)
from connected  user: Hello TechBeamers
Received from User: HELLO TECHBEAMERS
 ? Hello Dear Reader
from connected  user: You posts are awesome :)
Received from User: YOU POSTS ARE AWESOME :)
 ? Thank you very much. This is what keeps us motivated.
Copy the code
Python 3.51. (v3. 51.:37a07cee5969, Dec 6 201501:54:25) [MSC v1900. 64 bit (AMD64)] on win32
Type "copyright"."credits" or "license()" for more information.
 
 RESTART: C:\Users\Techbeamers\AppData\Local\Programs\Python\Python35\Python-Client.py 
 ? Hello TechBeamers

Received from server: Hello Dear Reader
 ? You posts are awesome :)

Received from server: Thank you very much. This is what keeps us motivated.
 ? q
Copy the code

Check program compatibility

Note that we have tested the above client-server code using Python version 3. But you can easily convert the above code to run on Python 2.7. You need to replace the following lines of code.

data = input("? ")
Copy the code

Use the following Python input functions for Python 2.7.

data = raw_input("? ")
Copy the code

We’ve listed more differences in the points below.

  • Some other functions in Python 2.7, such as printing, do not require closed braces.
  • None of Python 2.7’s socket functions (such as send()/recv()) need to decode their return value, as Python 3 does.

Quick summary — Python Socket programming

We hope that the above tutorial has given you some new knowledge about Socket programming in Python. If you enjoyed this article and are interested in seeing more of it, follow me here (Github/Gitee) for more information. Here is a summary of all my original and work source code

More on this at ๐Ÿงต

  • 30 Python tutorials and tips | Python theme month
  • Python statements, expressions, and indentation | Python theme month
  • Python keywords, identifiers, and variables | Python theme month
  • How to write comments and multi-line comments in Python | Python Theme Month
  • 20 Python Tips Everyone must Know | Python Theme month
  • Python data types — Basic to advanced learning | Python topic month
  • 100 Basic Python Interview Questions Part 1 (1-20) | Python topic month
  • 100 Basic Python Interview Questions Part 2 (21-40) | Python topic month
  • 100 Basic Python Interview Questions Part 3 (41-60) | Python topic month
  • 100 Basic Python Interview Questions Part 4 (61-80) | Python topic month
  • 100 Basic Python Interview Questions Part 5 (81-100) | Python topic month

Recommended articles of the past:

  • Teach you to use Java to make a gobang game
  • Interesting way to talk about the history of JavaScript โŒ›
  • The output of a Java program | Java exercises ใ€‘ ใ€ 7 sets (including parsing)
  • โค๏ธ5 VS Code extensions that make refactoring easy โค๏ธ
  • It is said that if you have light in your eyes, everywhere you go is light
  • 140000 | 400 multichannel JavaScript ๐ŸŽ“ interview questions with answers ๐ŸŒ  items (the fifth part 371-424)

If you do learn something new from this post, like it, bookmark it and share it with your friends. ๐Ÿค— Finally, don’t forget โค or ๐Ÿ“‘ for support