How to create a server and a client in python by using network sockets

The Python computer programming language offers a module which can be used to interact with the networking interface; this module is called socket. Having some experience with this module, I decided to share it through this article, with the main purpose of helping other Python geeks get familiar with networking.

Through this article, you are going to learn how to create a simple server and a client with the help of the Python’s socket module. Both the client and the server will be very simple, just to illustrate the power of the socket module in practice.

Before going any further with this article, make sure to create two scripts: client.py and server.py. Each one of them will store the code for scripting a client and a server wth the help of the socket module, which is offered by default in the Python computer programming language.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

What is a socket?

Based on my experience with sockets through the Python computer programming language, a socket is an endpoint of a bidirectional communications channel. Not only can sockets be implemented to communicate between processes on the same machine, but also to send and receive data through computers on different continents.

Enough theory, let’s put the Python’s socket module in practice.

Code the client.py

The script client.py will serve as a client, which will send a request to the TCP listening server. Once you have managed to open the script in editing mode, write the following line of Python code.

import socket #  it imports the socket module, which is offered by default

Now that we have managed to import the socket module in the client.py module, we have to create a new socket by making use of the Python code which is shown below.

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1'
port = 13

Once you have managed to create a fresh socket and also have defined the host and the port which the client will connect to, implement the Python code which is shown below in your client.py script.

client.connect((host, port))

The above function, part of the Python’s socket module, takes as an input a tuple which contains the host and the port which the client is going to connect to. Once the connection is being made, the client needs to receive data from the server.

The Python code which will be used to receive data from the server is being shown below.

data = client.recv(1024)
print(data)  # prints the data

In the end, the script client.py will look like the one which is being shown below.

import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1'
port = 13
client.connect((host, port))
data = client.recv(1024)
print(data)

Code the server.py module

The server.py module will store the code for the TCP listening server, a server which will wait for incoming connections from different clients.

Open the server.py module in editing mode and type the following piece of Python code with the main purpose of importing the socket module.

import socket

Once you have managed to import the socket module inside the server.py file, create a fresh socket like the one shown below.

server = socket.socket(socket.AF_STREAM, socket.SOCK_STREAM)

Then bind an address and a port to the server by making use of the Python code which is being shown below.

server.bind(('127.0.0.1', 13))

Now that you have managed to bind an address and a port to the server, make use of the following method to listen for incoming connections from different clients.

server.listen(5)

The TCP listener is being setup. Since the server.py should listen for incoming connections to infinite, we need a while True loop to achieve this task.

while True:
    connection, address = server.accept()
    print('Got connection from', address)
    connection.send('Welcome to the TCP listener')
    connection.close()  # close the connection

In the end, the server.py module should look like the one being shown below.

import socket
server = socket.socket(socket.AF_STREAM, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 13))
server.listen(5)
while True:
    connection, address = server.accept()
    print('Got connection from', address)
    connection.send('Welcome to the TCP listener')
    connection.close()  # close the connection

Run the client and the server

We have finally managed to code two simple modules, a client and a server. It is time to run them and see the results.

Open two terminal windows inside the folder in which you have stored both the client.py and server.py modules. We need to run the server first, so we can start the TCP listener to wait for incoming connections.

In the first terminal window, start the server by making use of the command which is shown below.

python server.py

Once you have managed to start the server, run the client.py the same way we used for the server.py script.

python client.py

If the code of both modules get executed successfully, the client and the server will communicate data to each other. On the terminal window in which you executed the server module, the following output should come out.

('Got connection from', ('127.0.0.1', 51444))

On the other hand, in the terminal window in which you executed the client, the following output should come out.

Welcome to the TCP listener

Final thoughts

The Python’s socket module is a very useful one when it comes to scripting applications that make use of the network interface. Through this article you learned how to code two simple modules, a client and a server. Although not very complex scripts, the client.py and the server.py make a perfect case for illustrating the powerful features of the Python’s socket module.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

3 thoughts on “How to create a server and a client in python by using network sockets”

  1. I am faced with this problem
    when I tried the server code that you write I am new this raspberry pi thing
    and python am just simply try copy past
    but I could not manage to get things done sorry for my poor english
    I want to learn how to do this
    specially connection between raspberry pi3 and pc with python without
    putty and ssh or vcn because ı did this
    I tried every other code on the internet and still empty handed please help me I beg you cause
    I tried so much but some how I dont know why this god punishment is not working
    when I used the 127.0.0.1 there is no any problem and probably with this way I am communicating with myself on raspberry pi
    actually but when I write my pi wlan0 ip to server and my pc ıp to client is not working
    there is no any connection any message under these circumstances it will be a gift from heaven
    I could not manage to send any message any signal any simple thing to my computer and
    I check the connection ı tried with ethernet cable with tcp with udp with wireless with blood magic result is
    gues what perfect zero help me please

    1. Traceback (most recent call last):
      File “/home/pi/Desktop/server5.py”, line 2, in
      server = socket.socket(socket.AF_STREAM, socket.SOCK_STRAM)
      AttributeError: module ‘socket’ has no attribute ‘AF_STREAM’

      this was my problem sorry my bad I did not send before but I am repeating again this is not the ony problem that I saw thank you for your patience

  2. You really make it seem really easy together with
    your presentation but I find this matter to be actually one thing which I feel
    I might never understand. It kind of feels too complicated and very broad
    for me. I am looking ahead for your subsequent publish, I will attempt to get the cling of it!

Leave a Reply

Your email address will not be published. Required fields are marked *