Python Socket Programming – Server, Client Example

Filed Under: Python

Good Day Learners! In our previous tutorial, we discussed about Python unittest module. Today we will look into python socket programming example. We will create python socket server and client applications.

Python Socket Programming

To understand python socket programming, we need to know about three interesting topics – Socket Server, Socket Client and Socket.

So, what is a server? Well, a server is a software that waits for client requests and serves or processes them accordingly.

On the other hand, a client is requester of this service. A client program request for some resources to the server and server responds to that request.

Socket is the endpoint of a bidirectional communications channel between server and client. Sockets may communicate within a process, between processes on the same machine, or between processes on different machines. For any communication with a remote program, we have to connect through a socket port.

The main objective of this socket programming tutorial is to get introduce you how socket server and client communicate with each other. You will also learn how to write python socket server program.

Python Socket Example

We have said earlier that a socket client requests for some resources to the socket server and the server responds to that request.

So we will design both server and client model so that each can communicate with them. The steps can be considered like this.

  1. Python socket server program executes at first and wait for any request
  2. Python socket client program will initiate the conversation at first.
  3. Then server program will response accordingly to client requests.
  4. Client program will terminate if user enters “bye” message. Server program will also terminate when client program terminates, this is optional and we can keep server program running indefinitely or terminate with some specific command in client request.

Python Socket Server

We will save python socket server program as To use python socket connection, we need to import socket module.

Then, sequentially we need to perform some task to establish connection between server and client.

We can obtain host address by using socket.gethostname() function. It is recommended to user port address above 1024 because port number lesser than 1024 are reserved for standard internet protocol.

See the below python socket server example code, the comments will help you to understand the code.

import socket

def server_program():
    # get the hostname
    host = socket.gethostname()
    port = 5000  # initiate port no above 1024

    server_socket = socket.socket()  # get instance
    # look closely. The bind() function takes tuple as argument
    server_socket.bind((host, port))  # bind host address and port together

    # configure how many client the server can listen simultaneously
    conn, address = server_socket.accept()  # accept new connection
    print("Connection from: " + str(address))
    while True:
        # receive data stream. it won't accept data packet greater than 1024 bytes
        data = conn.recv(1024).decode()
        if not data:
            # if data is not received break
        print("from connected user: " + str(data))
        data = input(' -> ')
        conn.send(data.encode())  # send data to the client

    conn.close()  # close the connection

if __name__ == '__main__':

So our python socket server is running on port 5000 and it will wait for client request. If you want server to not quit when client connection is closed, just remove the if condition and break statement. Python while loop is used to run the server program indefinitely and keep waiting for client request.

Python Socket Client

We will save python socket client program as This program is similar to the server program, except binding.

The main difference between server and client program is, in server program, it needs to bind host address and port address together.

See the below python socket client example code, the comment will help you to understand the code.

import socket

def client_program():
    host = socket.gethostname()  # as both code is running on same pc
    port = 5000  # socket server port number

    client_socket = socket.socket()  # instantiate
    client_socket.connect((host, port))  # connect to the server

    message = input(" -> ")  # take input

    while message.lower().strip() != 'bye':
        client_socket.send(message.encode())  # send message
        data = client_socket.recv(1024).decode()  # receive response

        print('Received from server: ' + data)  # show in terminal

        message = input(" -> ")  # again take input

    client_socket.close()  # close the connection

if __name__ == '__main__':

Python Socket Programming Output

To see the output, first run the socket server program. Then run the socket client program. After that, write something from client program. Then again write reply from server program. At last, write bye from client program to terminate both program. Below short video will show how it worked on my test run of socket server and client example programs.

python socket programming, python socket server

pankaj$ python3.6 
Connection from: ('', 57822)
from connected user: Hi
 -> Hello
from connected user: How are you?
 -> Good
from connected user: Awesome!
 -> Ok then, bye!

pankaj$ python3.6 
 -> Hi
Received from server: Hello
 -> How are you?
Received from server: Good
 -> Awesome!
Received from server: Ok then, bye!
 -> Bye

Notice that socket server is running on port 5000 but client also requires a socket port to connect to the server. This port is assigned randomly by client connect call. In this case, it’s 57822.

So, that鈥檚 all for Python socket programming, python socket server and socket client example programs.

Reference: Official Documentation


  1. Nathan says:

    hi! thank u for the tutorial. i want to learn back end (server) development full. can u teach me pls!

  2. Sudhi says:

    Once the socket is connected from Client to Server, is it possible that Server can send the data to Client, whenever a data is available for the Client, without getting an heart beat (request) from the Client.

  3. pi says:

    馃檹 馃殌 馃幆
    Dead on target.
    Works out of the box.

  4. Rohit says:

    c.send(bytes(message,’utf-8′) )# send message
    OSError: [WinError 10038] An operation was attempted on something that is not a socket
    what should i do?

  5. MHC says:

    Hello, I have a question. Instead of sending a message, I want to send an audio or a video. What should I change in the code?

  6. Addisu says:

    how to reject a client with the same username in python code?

  7. Kick says:

    This is a perfect one which i’m looking, but can you please guide me to save the output data to the mysql database in python, its really so important for me to complete that. Thanks in advance, hope you respond soon enough.

    1. Pankaj says:

      Please checkout this tutorial to save data into MySQL database: Python MySQL

      1. Mausam Kaushal says:

        hello bhai. aapki help chahiye thi. Asal me mai ek quiz app bana raha hun . mai chahta hun ki mai quiz form bana ke online dynamically usse clients tak pohchaun or vo usse bharen. Aapne iss me data send karna to bata diya but only text share karna bataya. Maai unhe ek input bhejna chahta hun jisse vo ek option choose kar saken. Also mujhe kaam shuru karne ke liye module suggest kar do like kivy, pyramid, Django etc. Please bhai reply soon.

  8. Shubham says:

    Sir what is the programming to send continuously more than one message from client side and receive from server side (vice verse )

  9. makaaka says:

    Thanks a lot for the code. what ip address and port number can you offer if you are using VNC service to connect two devices?

  10. Shiva says:

    thanks its very simple code working on my pc, phone and Tab

    1. naya says:

      Hi Shiva, what are some of the implementation you did for the code work on your phone and pc?
      pls my mail–>

      1. naya says:

        Hi there!
        How can I implement this code as DHCP OR TFTP file.
        Any help i will appreciate!

  11. vivek says:

    thanks for this code u re solve my problems

  12. bindu says:

    How can we compile this with python not with python3

    1. Pankaj says:

      Just create an alias of “python” to python3.7. I have different versions of Python installed, that’s why there are many aliases.

      1. bindu says:

        but with python i not able to get output
        Traceback (most recent call last):
        File “”, line 26, in
        File “”, line 12, in client_program
        message = input(” ->1 “) # take input
        File “”, line 1, in
        NameError: name ‘hi’ is not defined
        this is what i’m getting when i compile with python but with python3 i’m getting output very well

        1. nosee says:

          it seems that your compiler is reading the message as variable name and not as a value so maybe this will work

          message = str(input(“–>”))

        2. Sankalp says:

          use raw_input instead of input

  13. Mihailo Raskovic says:

    Very nice from you. Just carry on.

  14. Nagesh says:

    Simple example. Thanks.

  15. Basavaraj Hunshal says:

    It works at localhost nicely… Thank you friend

  16. sdd says:

    File “C:/Users/hp/AppData/Local/Programs/Python/Python37/”, line 25, in
    File “C:/Users/hp/AppData/Local/Programs/Python/Python37/”, line 9, in client_program
    client_socket.connect((host, port)) # connect to the server
    ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
    I am getting this error

    1. Guna says:

      same error here

    2. Lonwe Simtado says:

      Run server before client.

  17. sanjay says:

    how do we chat with different persons should we give client program to them and ask to run. and i would host the server in my pc



      in server program
      host=’ ‘
      and in client program
      host=”ip address of server machine”

      1. aman says:

        it is not working as per your instructions

        1. Botshelo says:

          Hey can you help me with that…im struggling to do it correctly

  18. adarsh says:

    host = socket.gethostname()
    AttributeError: ‘module’ object has no attribute ‘gethostname’

    im getting this error..

  19. Aditya raj says:

    your server code is wrong you have to use different names to send the data

    data = conn.recv(1024).decode()
    if not data:
    # if data is not received break
    print(“from connected user: ” + str(data))
    message = input(‘ -> ‘) #use different name at the place of data
    conn.send(message.encode()) # send data to the client

    1. nosee says:

      it’s not wrong in fact it’s more efficient this way but yes reassigning variables makes codes harder to read and maintain

  20. amrane says:

    Good Job

  21. Synapsensalat says:

    Great little example, thanks!

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content