Simple Chat server in Python

How to build a simple chat server with Python

Hello world, it’s me again; in today’s post we will learn how to build a simple chat server with Python. Yeah a chat server an application that host’s chats, how cool would that be huh?? to be able to chat with your friend or colleague who is on another machine. We achieve this awesome feat with the help of Python’s socket module.
Though the chat server only works on machines on the same network, it’s still cool to learn how chat server’s work by building one.

Getting started:

We will use the socket module, which is a standard python module(no need for pip install or anything). This project is pretty simple like I mentioned earlier just a few lines of code, well enough talks let’s get to it; the project is divided into two parts the server side and the client side. The server side initiates a connection medium which the client connects to, then messages can be sent back and forth by both parties.

Server side:

First we will import the socket module and assign our port and host name.

import socket
#server
# TCP Server Code
 
host="0.0.0.0"                # Set the server address to variable host
port=33000  

We will then create a socket object and bind our hostname and port number to it.

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create socket
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #prevents timeouts

sock.bind((host,port))# bind server address

Now we will listen for connections from the client, once there is a connection we will accept the connection retrieving the client’s IP address.

sock.listen(1000) # Sets socket to listening state with a  queue of 1000 connection
print("Listening for connections.. ")
client,address = sock.accept()               # Accepts incoming request from client and returns
print(f"{address} just connected !!")

Once we accept the connection we will enter into an explicit loop, in this loop we will send and receive messages from the client.

while True:                                    # socket and address to variables q and addr
    try:
        data = input("Enter data to be sent:  ")  # Data to be sent                                          # user
        client.send(data.encode("ascii")) # Sends data to client
    except:
        pass
    try:
        msg = client.recv(1024)# Receives data upto 1024 bytes
        print("Message from client : " + msg.strip().decode('ascii'))
    except Exception as e:
        print(e)
 
sock.close()
# End of code

………

Notice how the socket’s send and recv method always have an encode and decode function behind the string, socket module only sends bytes so we encode the message in ASCII when sending and decode the message with ASCII so we can work with the message as a string.

Client side:

Same as the client module, we will import the socket module and declare our hostname and port these must correspond with that of the sever.

import socket
#Client
# TCP Client Code
 
host="0.0.0.0"            # Set the server IP address
port = 33000               # Sets the variable port to 4444
 

We will create a socket object and connect to the server via the hostname and port number of the sever.

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create socket
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #prevents timeouts

sock.connect((host,port))# Connect to server address

Now we will also enter into an explicit loop, in this loop we will receive and send messages back and forth to the server.

print("Connected to Server !!!")
while True: 
    msg = sock.recv(1024)# Receives data upto 1024 bytes
    data = msg.strip().decode('ascii') 
    print("Message from server : " + data)
    response = input("Me ::")
    sock.send(response.encode("ascii"))
    

sock.close()# Closes the socket 
# End of code

Note also the encoding and decoding.

The application in action:

Here we can see how the application worked in my local machine. This image is from the server side.

Simple Chat server with Python

Conclusion:

You have learnt how to build a simple chat server with Python. It doesn’t end there, you can improve on this example like chat with multiple people. Python’s socket module is really cool, here is an example of what else you can use it for. Get the complete code from my repo.

Leave a Reply

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