5 Easy Way to Build a Python Chat room

5 Tips to build a GUI Python Chatbox

Hello, the Codezine fams we are back again with another python #DIY tutorial. Today, we are going a Python Chat Room or you can say Python Chatbox which is simple to understand & run. Excited? If so, let’s move on to the building concept of our Gui python chat room.

Note: You don’t have to install any python packages for this project.

Concept:

Basically, The Python Chatbox uses the concept of Socket Programming & Multi-threading. There are two sections for the chatbot i.e server-side program called socketserver.py & client-side program namely chat.py. It allows a chat room or chat box to connect with multiple users at the same time. But, before moving to the next stage we will learn Socket Programming & Multi-threading. Without knowing it will be difficult for a beginner to understand while building the project.

Socket Programming:

Generally speaking, Sockets can be explained as the endpoints in a communication channel that are bi-directional and helps to join communication between a server and one or more client groups. Literally, it allows a client to interact with other clients through the server.

Multi-threading

A multi-thread is a subprocess that helps to runs a lay of commands individually of any other thread. When the user connects to the server, a different thread creates and communication from the server to the client takes place along separate threads based on the socket objects build for the specification of each client.

Working of Chatbox: Our chat room/ chatbox uses the local Ip address of the machine[PC] while communicating between server-side script & client-side script. Whenever a client will connect to the chat room it will display “connection established” in the server-side script & will allow chats to work. The chatbox is designed to work with multiple clients & work with a definite local IP. It in turn prevents the complexity of running the program for an individual.

The requirement for Project:

  • A good PC having at least an I5 core processor that runs any sort of program.
  • A notebook to write comments.
  • An Ide typically VS Code Editor, Atom, or Sublime.
  • Most importantly you must have python installed on your PC to perform any python programs.
  • Your Concentration.

How to build a Python Chatbox or python Chat Room?

  • Make a folder called python chatbox or chatroom on your desktop where you can put all files.
  • After that, drag your files to your code ide & create two files namely chat.py[Client-Side Script]/[GUI part] & socketserver.py[Server-side script].

Note: There is no need to install any python package as everything is inbuilt after you install python.

  • Put the codes given below by seeing the detailed notations given below to their respective files.
  • Run the program by first performing python socketserver.py & after that python chat.py.
  • That’s it test your chatbox if it works & finally your #DIY project is completed. 🙂

Codes:

socketserver.py

##Python codes to do server-side part of chat room.
import _thread
import socket
import threading
"""AF_INET is the address domain of the 
socket. This is used when we have an Internet Domain with 
any two hosts The 2nd context of the code is the type of socket. """
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)  
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
# piece of code to allow IP address & Port
host="127.0.0.1"
port=5000
s.bind((host,port))
s.listen(5)
clients=[]
#code to allow users to send messages
def connectNewClient(c):
     while True:
        global clients
        msg = c.recv(2048)
        msg ='Online ('+str(clients.index(c)+1)+'):  '+msg.decode('ascii')
        sendToAll(msg,c)
def sendToAll(msg,con):
    for client in clients:
        client.send(msg.encode('ascii')) 
        
while True:
    c,ad=s.accept()
    # Display message when user connects
    print('*Server Connected ')
    clients.append(c)
    c.send(('Online ('+str(clients.index(c)+1)+')').encode('ascii'))
    _thread.start_new_thread(connectNewClient,(c,))

chat.py[Gui Part]

#Gui Programming Part
import tkinter
import socket
import _thread
import sys

# Code to create a new client socket  and connect to the server

i = 3
client = 0
start = True
def sendMessage ():
    msg = txt.get()
    client.send(msg.encode('ascii'))

def recievingMessage (c): 
    global i
    while True :
        msg=c.recv(2048).decode('ascii')
        if not msg :
            sys.exit(0)
        global start
        if (start) :
            start = False
            #tkinter codes starts
            window.title(msg)
            continue
        msglbl = tkinter.Label(window,text=msg)
        msglbl['font']=("Courier",10)
        msglbl['bg']='black'
        msglbl['fg']='#0aff43'
        msglbl['width']=50
        msglbl.grid(columnspan=2,column=0,row=i,padx=5)
        i += 1
#Socket Creation
def socketCreation ():    
    c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    c.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
#Local Host    
# import all functions /
#  everthing from chat.py file
    host = '127.0.0.1'
    port = 5000
    c.connect((host,port))
    global client
    client = c
    send['command'] = sendMessage
    _thread.start_new_thread(recievingMessage, (c,) )


#Creating a window
window = tkinter.Tk()
window.title('Chatbox')
window['bg']='#242424'

window['padx']=10
window['pady']=10
#Adding Elements
#Entry
txt = tkinter.Entry(window)
txt['width']=50
txt['relief']=tkinter.GROOVE
txt['bg']='#f5f6f7'
txt['fg']='red'
txt['font']=("Courier",12)
txt.grid(column=0,row=1,padx=5,pady=15)
#Button
send = tkinter.Button(window,text="Send")
send['relief']=tkinter.GROOVE
send['bg']='red'
send['fg']='white'
send['activebackground']='#404040'
send['padx']=3
send['font']=("Courier",10)
send.grid(column=1,row=1,padx=5,pady=15)


_thread.start_new_thread(socketCreation, () )


window.mainloop()    

Conclusion

The important code notation is given above each line of codes, so we haven’t provided in a different section. The notation will help you to know the working of each codes in details. Lastly, follow all the steps carefully which will prevent any unavoidable circumstances which running the programs. Thank you & share it, if you find it useful.

5 thoughts on “5 Easy Way to Build a Python Chat room

  1. Joseph Santhosh says:

    I have saved all the code in each file but I have no code in the main.py so it won’t run. Could you help me please?

  2. Vũ Thành Trung says:

    Can you fix this error?:
    Exception ignored in thread started by:
    Traceback (most recent call last):
    File “i:/chat/chat.py”, line 44, in socketCreation
    c.connect((host,port))
    ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.