I don't know about you but I do miss those days when there was no such thing as facebook, no Android phone and IPhone. But we did have Cyber Cafe where we used to have our favorite Yahoo Messenger installed where we used to spend hours and hours with unknown friends and the whole experience of it was very cozy. So I thought why not create something of that sort using python.
Which would look like this:-
Lets get on with the code:-
Run the server script.
# Import required modules import socket import threading HOST = '127.0.0.1' PORT = 1234 # You can use any port between 0 to 65535 LISTENER_LIMIT = 5 active_clients = [] # List of all currently connected users # Function to listen for upcoming messages from a client def listen_for_messages(client, username): while 1: message = client.recv(2048).decode('utf-8') if message != '': final_msg = username + '~' + message send_messages_to_all(final_msg) else: print(f"The message send from client {username} is empty") # Function to send message to a single client def send_message_to_client(client, message): client.sendall(message.encode()) # Function to send any new message to all the clients that # are currently connected to this server def send_messages_to_all(message): for user in active_clients: send_message_to_client(user[1], message) # Function to handle client def client_handler(client): # Server will listen for client message that will # Contain the username while 1: username = client.recv(2048).decode('utf-8') if username != '': active_clients.append((username, client)) prompt_message = "SERVER~" + "\u0332".join(f"{username} ")+ " joined the chatroom" send_messages_to_all(prompt_message) break else: print("Client username is empty") threading.Thread(target=listen_for_messages, args=(client, username, )).start() # Main function def main(): # Creating the socket class object # AF_INET: we are going to use IPv4 addresses # SOCK_STREAM: we are using TCP packets for communication server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creating a try catch block try: # Provide the server with an address in the form of # host IP and port server.bind((HOST, PORT)) print(f"Running the server on {HOST} {PORT}") except: print(f"Unable to bind to host {HOST} and port {PORT}") # Set server limit server.listen(LISTENER_LIMIT) # This while loop will keep listening to client connections while 1: client, address = server.accept() print(f"Successfully connected to client {address[0]} {address[1]}") threading.Thread(target=client_handler, args=(client, )).start() if __name__ == '__main__': main()
Copied
Distribute the Client script to other computers connected with the same network.
# import required modules import socket import threading import tkinter as tk from tkinter import scrolledtext from tkinter import messagebox HOST = '127.0.0.1' PORT = 1234 DARK_PURPLE = '#500F4B' MEDIUM_PURPLE = '#77246F' OCEAN_BLUE = '#77246F' WHITE = "white" FONT = ("Arial", 17) BUTTON_FONT = ("Arial", 15) SMALL_FONT = ("Arial", 13) # Creating a socket object # AF_INET: we are going to use IPv4 addresses # SOCK_STREAM: we are using TCP packets for communication client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def add_message(message): message_box.config(state=tk.NORMAL) message_box.insert(tk.END, message + '\n') message_box.config(state=tk.DISABLED) def connect(): # try except block try: # Connect to the server client.connect((HOST, PORT)) print("Successfully connected to server") add_message("[SERVER] Successfully connected to the server") except: messagebox.showerror("Unable to connect to server", f"Unable to connect to server {HOST} {PORT}") username = username_textbox.get() if username != '': client.sendall(username.encode()) else: messagebox.showerror("Invalid username", "Username cannot be empty") threading.Thread(target=listen_for_messages_from_server, args=(client, )).start() username_textbox.config(state=tk.DISABLED) username_button.config(state=tk.DISABLED) def send_message(): message = message_textbox.get() if message != '': client.sendall(message.encode()) message_textbox.delete(0, len(message)) else: messagebox.showerror("Empty message", "Message cannot be empty") root = tk.Tk() root.geometry("600x600") root.title("Messenger Client") root.resizable(False, False) root.grid_rowconfigure(0, weight=1) root.grid_rowconfigure(1, weight=4) root.grid_rowconfigure(2, weight=1) top_frame = tk.Frame(root, width=600, height=100, bg=DARK_PURPLE) top_frame.grid(row=0, column=0, sticky=tk.NSEW) middle_frame = tk.Frame(root, width=600, height=400, bg=MEDIUM_PURPLE) middle_frame.grid(row=1, column=0, sticky=tk.NSEW) bottom_frame = tk.Frame(root, width=600, height=100, bg=DARK_PURPLE) bottom_frame.grid(row=2, column=0, sticky=tk.NSEW) username_label = tk.Label(top_frame, text="^", font=('Webdings',17), bg=DARK_PURPLE, fg=WHITE) username_label.pack(side=tk.LEFT, padx=0) username_label = tk.Label(top_frame, text="Enter Username:", font=FONT, bg=DARK_PURPLE, fg=WHITE) username_label.pack(side=tk.LEFT, padx=10) username_textbox = tk.Entry(top_frame, font=FONT, bg=MEDIUM_PURPLE, fg=WHITE, width=23) username_textbox.pack(side=tk.LEFT) username_button = tk.Button(top_frame, text="Join", font=BUTTON_FONT, bg=OCEAN_BLUE, fg=WHITE, command=connect) username_button.pack(side=tk.LEFT, padx=15) message_textbox = tk.Entry(bottom_frame, font=FONT, bg=MEDIUM_PURPLE, fg=WHITE, width=38) message_textbox.pack(side=tk.LEFT, padx=10) message_button = tk.Button(bottom_frame, text="Send", font=BUTTON_FONT, bg=OCEAN_BLUE, fg=WHITE, command=send_message) message_button.pack(side=tk.LEFT, padx=10) message_box = scrolledtext.ScrolledText(middle_frame, font=SMALL_FONT, bg=MEDIUM_PURPLE, fg=WHITE, width=67, height=26.5) message_box.config(state=tk.DISABLED) message_box.pack(side=tk.TOP) def listen_for_messages_from_server(client): while 1: message = client.recv(2048).decode('utf-8') if message != '': username = message.split("~")[0] content = message.split('~')[1] add_message(f"[{username}] {content}") else: messagebox.showerror("Error", "Message recevied from client is empty") # main function def main(): root.mainloop() if __name__ == '__main__': main()
Copied
This is how it would look:
Comments
Post a Comment