Python is one of the most versatile programming languages ​​and it can be observed through its various applications everywhere. In this tutorial, we will create a group chat room that can host more than two clients at a time. The server-client architecture means that multiple clients will be hosted by a single server. We will import two libraries named ‘socket’ and ‘threading’. Both are built-in libraries, so there is no need to install them by pip. We need to write two scripts, one for the server side and the other for the client side.

Yashraj Singh Chouhan

Human by life, programmer by choice

twitter social iconLinkedIn social icon

Simple chat room using Python

Python is one of the most versatile programming languages ​​and it can be observed through its various applications everywhere. Here is an example of how you can create a simple command line based chat room using python which is easy to implement and understand. So let’s get started.

What is a chat room?

A chat room is a medium/interface that allows two or more people to chat and send messages to everyone. It can also be an interpersonal (one-to-one) chat and a group chat. In this tutorial, we will create a group chat room that can host more than two clients at a time.

Architecture

For the chat room, we will use the server-client architecture. This means that multiple clients will be hosted by a single server.

Begin:

Before diving into the code, the last thing we want to know is to follow this architecture, we need to write two scripts, one for the server side and the other for the client side. One thing that needs to be very clear is that clients will only talk through the server. There will be no direct communication between them. So let’s dive into the code.

Server side code:

First, we’ll import two libraries named ‘socket’ and ‘threading’. Both are built-in libraries, so there is no need to install them by pip. Just importing will work. Socket programming is a way to connect two nodes over a network to communicate with each other, while the threading module provides a very easy and intuitive API to spawn multiple threads in a program. Next, we’ll move on to setting our IP and port. Be aware that only non-reserved ports can be used because it will work on LocalHost and the computer may cause problems if you use the reserved ports.

When defining socket, two parameters named (AF_INET) and (SOCK_STREAM) will be used. The first indicates the use of the Internet socket and the other indicates the use of TCP. Next, we move on to the definition of the broadcast function. Its basic function is to send a message to customers from the customer list. This function is not yet retiring. We will also use it in other places. Managing clients is quite a tough job, and so is the function. It first tries if a message can be received from the client side, if so it is broadcast.

But if there is any type of error/problem, the server keeps things simple. It just deletes the client. We’ve done a lot of work, but adding customers is still waiting. So let’s do it now. In the receive function, the keyword ‘NICKNAME’ is sent to clients, which means that their nickname is requested. Later, after getting the nickname, he adds the client to the list.

Well, this loop remains active and multiple clients can join the server. Everything you need to get the right IP and port address.

Coded:

#Coded by Yashraj Singh Chouhan
import socket, threading                                                #Libraries import

host = '127.0.0.1'                                                      #LocalHost
port = 7976                                                             #Choosing unreserved port

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)              #socket initialization
server.bind((host, port))                                               #binding host and port to socket
server.listen()

clients = []
nicknames = []

def broadcast(message):                                                 #broadcast function declaration
    for client in clients:
        client.send(message)

def handle(client):                                         
    while True:
        try:                                                            #recieving valid messages from client
            message = client.recv(1024)
            broadcast(message)
        except:                                                         #removing clients
            index = clients.index(client)
            clients.remove(client)
            client.close()
            nickname = nicknames[index]
            broadcast('{} left!'.format(nickname).encode('ascii'))
            nicknames.remove(nickname)
            break

def receive():                                                          #accepting multiple clients
    while True:
        client, address = server.accept()
        print("Connected with {}".format(str(address)))       
        client.send('NICKNAME'.encode('ascii'))
        nickname = client.recv(1024).decode('ascii')
        nicknames.append(nickname)
        clients.append(client)
        print("Nickname is {}".format(nickname))
        broadcast("{} joined!".format(nickname).encode('ascii'))
        client.send('Connected to server!'.encode('ascii'))
        thread = threading.Thread(target=handle, args=(client,))
        thread.start()

receive()

Client side code:

This is our second code where we will write the script for our clients. This code will be enough to get us several customers without any problem. So we start by importing socket and threading. After initializing the socket, we need to connect it to the IP and port. They must be identical to the server to make it functional.

Now we need to connect to the server and if you remember that ‘NICKNAME’ was the keyword sent by the server to request a nickname, if the client receives it, it sends the nickname and enters the chat room. But if it does not receive this keyword, the connection is lost. Now that we are connected to the server, why are we waiting, let’s start messaging.

For this, we have the write function which manages the sending of messages. If you’re wondering what about receiving messages, remember that we imported chat threads. Here it comes in, we need two threads to start and it’s done.

You noticed that we encoded the messages in ASCII before sending them, this is because we can only send messages as bytes and not as a string. That’s why always remember to encode before sending and decode after receiving.

coded:

#Coded by Yashraj Singh Chouhan
import socket, threading
nickname = input("Choose your nickname: ")

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)      #socket initialization
client.connect(('127.0.0.1', 7976))                             #connecting client to server

def receive():
    while True:                                                 #making valid connection
        try:
            message = client.recv(1024).decode('ascii')
            if message == 'NICKNAME':
                client.send(nickname.encode('ascii'))
            else:
                print(message)
        except:                                                 #case on wrong ip/port details
            print("An error occured!")
            client.close()
            break
def write():
    while True:                                                 #message layout
        message = '{}: {}'.format(nickname, input(''))
        client.send(message.encode('ascii'))

receive_thread = threading.Thread(target=receive)               #receiving multiple messages
receive_thread.start()
write_thread = threading.Thread(target=write)                   #sending messages 
write_thread.start()

Test in the real world:

Remember that the server will run first, then multiple clients can join. This can be run in command line, but we need different terminals to run them individually.

Well that’s it for this code, I hope you liked it!

LOADING
. . . comments & After!