Code and Debug > Blog > Project > Python Project > Major Python Project > Live Group Chat using Python
Live Group Chat using Python
- November 12, 2022
- Posted by: Code and Debug
- Category: Major Python Project Project
No Comments

In this blog, you will get the full source code for creating a Live Chat Room using Python modules. A person can create a room and multiple users can join room by entering room name.
Running our Project
Below are the steps to run the project.
1. Copy the content of source code (at the end of page) into these 2 files in whichever folder you like.

2. Open Command Promt (cmd) in the folder where you created the files by pressing CTRL+L.

3. Run the following command to start the server to which people can connect and chat together.
python server.py

4. It will ask you to enter IP Address, if you don't know your IP address, just press ENTER. After that create a room with any name as per your preference. It will then wait for users to connect.
Note Down the SERVER IP ADDRESS and PORT.

5. Open new Command Prompt (CMD) again as shown in Step-2 and type in the following command so that user can connect to server.
python client.py

6. Enter the IP ADDRESS and PORT you will get when you start the server.

7. After successfully typing all the details correct, a window will open where you will be asked to type your name and start chatting.

8. Let's connect another user. Follow the same steps 5,6,7 to run another client and connect again from another user.

9. After connecting, all the users will get notified about new user connecting in the room, and thus now all users in a room can chat together.
2 Users Chatting Together

3 Users Chatting Together

10. You can quit the room by typing {quit} and all users in the group will be notified when someone quits the group.

Source Code
SERVER.PY
from socket import AF_INET, SOCK_STREAM
from threading import Thread
import sys
import socket
def accept():
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
client.send(bytes("Welcome to %s! Now type your name and press enter!" % (server_name), "utf8"))
addresses[client] = client_address
Thread(target=cclient, args=(client,)).start()
def cclient(client):
name = client.recv(BUFSIZ).decode("utf8")
welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % name
client.send(bytes(welcome, "utf8"))
msg = "%s has joined the chat!" % name
broadcast_to_all(bytes(msg, "utf8"))
clients[client] = name
while True:
msg = client.recv(BUFSIZ)
if msg != bytes("{quit}", "utf8"):
broadcast_to_all(msg, name + ": ")
else:
del clients[client]
# client.send(bytes("{quit}", "utf8"))
aa = "%s has left the chat." % name
broadcast_to_all(bytes(aa, "utf8"))
# client.close()
break
def broadcast_to_all(msg, prefix=""):
for sock in clients:
sock.send(bytes(prefix, "utf8") + msg)
clients = {}
addresses = {}
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Enter IP Address to host the server. Press ENTER to use default IP Address (%s)" % (IPAddr))
HOST = input("->")
if not HOST:
HOST = str(IPAddr)
PORT = 33000
server_name = ""
while server_name == "":
server_name = input("Enter the room name -> ")
if server_name == "":
print("Room name cannot be blank.")
BUFSIZ = 1024
ADDR = (HOST, PORT)
SERVER = socket.socket(AF_INET, SOCK_STREAM)
try:
SERVER.bind(ADDR)
except Exception as e:
print(e)
sys.exit()
if __name__ == "__main__":
SERVER.listen(6)
print("\nServer IP Address = %s" % (HOST))
print("Server PORT Number = %d" % (PORT))
print("Room Name = %s" % (server_name))
print("\nWaiting for connections...")
accepting_thread = Thread(target=accept)
accepting_thread.start()
accepting_thread.join()
SERVER.close()
CLIENT.PY
import sys
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import tkinter
from tkinter import font
def receive():
while True:
try:
msg = client_socket.recv(BUFSIZ).decode("utf8")
message_lists.insert(tkinter.END, msg)
message_lists.see(tkinter.END)
except OSError:
break
def send(event=None):
try:
msg = my_message.get()
my_message.set("")
client_socket.send(bytes(msg, "utf8"))
if msg == "{quit}":
client_socket.close()
top.quit()
except ConnectionResetError:
msg = "Server has been shut down. You may close this window."
message_lists.insert(tkinter.END, msg)
message_lists.see(tkinter.END)
def on_closing(event=None):
my_message.set("{quit}")
send()
top.quit()
HOST = input("Enter Server IP Address = ")
print("Enter PORT number. Leave blank if you dont know the port number.")
try:
PORT = input("-> ")
if not PORT:
PORT = 33000
else:
PORT = int(PORT)
except ValueError:
print("Port should be a number.")
sys.exit()
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
try:
client_socket.connect(ADDR)
except ConnectionRefusedError:
print("Cant connect to server.")
sys.exit()
except TimeoutError:
print("A connection attempt failed because the connected party did not properly respond after a period of time.")
sys.exit()
except Exception as e:
print(e)
sys.exit()
top = tkinter.Tk()
top.title("Chat Room")
framee = tkinter.Frame(top)
my_message = tkinter.StringVar()
my_message.set("")
scrollbar = tkinter.Scrollbar(framee)
small_font = font.Font(size=10)
message_lists = tkinter.Listbox(framee, height=20, width=70, yscrollcommand=scrollbar.set, font=small_font)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
message_lists.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
message_lists.pack()
framee.pack()
fields = tkinter.Entry(top, textvariable=my_message)
fields.bind("", send)
fields.pack()
send_button = tkinter.Button(top, text="Send", command=send)
send_button.pack()
top.protocol("WM_DELETE_WINDOW", on_closing)
receive_thread = Thread(target=receive)
receive_thread.start()
tkinter.mainloop()