[go: up one dir, main page]

0% found this document useful (0 votes)
23 views7 pages

Instant Messaging

The document contains source code for a messaging server and client that allows users to register, login, view online users, and send messages to each other. The server code handles connections from clients and stores user data in a database. The client code allows users to register, login, view online users, and send messages. Sample output shows the process of users registering, logging in, viewing online users, and sending messages between clients.

Uploaded by

Atif Mughal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views7 pages

Instant Messaging

The document contains source code for a messaging server and client that allows users to register, login, view online users, and send messages to each other. The server code handles connections from clients and stores user data in a database. The client code allows users to register, login, view online users, and send messages. Sample output shows the process of users registering, logging in, viewing online users, and sending messages between clients.

Uploaded by

Atif Mughal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

PROJECT

EECS563

DECEMBER 7, 2023
MAX DJAFAROV
Instant Messaging Platform

Source Code for Server

import socket
import threading
import sqlite3

# Function to initialize the database


def init_db():
conn = sqlite3.connect('user_database.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
password TEXT
)
''')
conn.commit()
conn.close()

# Function to check user credentials in the database


def check_credentials(username, password):
conn = sqlite3.connect('user_database.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?',
(username, password))
result = cursor.fetchone()
conn.close()
return result is not None
# Function to add a new user to the database
def add_user(username, password):
conn = sqlite3.connect('user_database.db')
cursor = conn.cursor()
cursor.execute('INSERT INTO users (username, password) VALUES (?, ?)',
(username, password))
conn.commit()
conn.close()

# Function to handle client connections


def handle_client(client_socket, address):
print(f"Accepted connection from {address}")
client_socket.send("Welcome to the messaging platform!\n".encode())

while True:
data = client_socket.recv(1024).decode().strip()
if not data:
break

command, *message = data.split()

if command == "register":
if len(message) == 2:
username, password = message
if check_credentials(username, password):
client_socket.send("Username already exists!\n".encode())
else:
add_user(username, password)
client_socket.send("Registration successful!\n".encode())
else:
client_socket.send("Invalid command format!\n".encode())

elif command == "login":


if len(message) == 2:
username, password = message
if check_credentials(username, password):
client_socket.send("Login successful!\n".encode())
online_users[username] = client_socket
show_online_users(client_socket)
else:
client_socket.send("Invalid username or
password!\n".encode())
else:
client_socket.send("Invalid command format!\n".encode())

elif command == "send":


if len(message) >= 2:
recipient, *msg = message
msg = ' '.join(msg)
if recipient in online_users:
recipient_socket = online_users[recipient]
recipient_socket.send(f"Message from {username}:
{msg}\n".encode())

else:
client_socket.send(f"{recipient} is not
online!\n".encode())
else:
client_socket.send("Invalid command format!\n".encode())

# Function to show online users


def show_online_users(client_socket):
online_usernames = ", ".join(list(online_users.keys()))
client_socket.send(f"Online users: {online_usernames}\n".encode())

# Initialize the database


init_db()

# Create a TCP/IP socket


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to a host and port


server_socket.bind(('localhost', 8888))

# Listen for incoming connections


server_socket.listen(5)
print("Server is listening for connections...")

# Dictionary to track online users and their respective sockets


online_users = {}

# Accept incoming connections and start a thread for each client


while True:
client_socket, address = server_socket.accept()
client_handler = threading.Thread(target=handle_client,
args=(client_socket, address))
client_handler.start()
Source Code for Client

import socket

# Create a TCP/IP socket


client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server


client_socket.connect(('localhost', 8888))

# Receive welcome message from the server


print(client_socket.recv(1024).decode())

while True:
option = input("Enter 'login' to log in or 'signup' to register: ")
if option.lower() == 'login':
# Get user inputs for login
username_login = input("Enter username to login: ")
password_login = input("Enter password to login: ")

# Login as a registered user


client_socket.send(f"login {username_login}
{password_login}\n".encode())
login_status = client_socket.recv(1024).decode()
print(login_status)

if login_status == "Login successful!\n":


while True:
option = input("Enter 'list' to see online users or 'send user
message' to send a message: ")
client_socket.send(option.encode())

if option.lower().startswith("list"):
online_users = client_socket.recv(1024).decode()
print(online_users)
elif option.lower().startswith("send"):
client_socket.send(option.encode())
send_status = client_socket.recv(1024).decode()
print(send_status)
else:
print("Invalid option entered!")
continue
break

elif option.lower() == 'signup':


# Get user inputs for registration
username_reg = input("Enter username to register: ")
password_reg = input("Enter password to register: ")
# Register a new user
client_socket.send(f"register {username_reg}
{password_reg}\n".encode())
print(client_socket.recv(1024).decode())

else:
print("Invalid option entered! Please enter 'login' or 'signup'.")
continue

# Close the connection


client_socket.close()

SAMPLE OUTPUT
First of all, the server file is run and it successfully starts listening for connections.

After that, the client file is run. It shows the welcome message and ask for login and signup. If

the user is already registered, then one should go for ‘login’ option. Otherwise, go for ‘signup’.

If user is already registered, it will show that the user already exists.

Now, choose the ‘login option.


Now, run the client code for another user.

After successful login, it will ask whether you want to see online users list or send message to

anyone.

If the option ‘list’ is selected, then it will show the list of online users.

Now, a message a sent to the user ‘david’ using this command ‘send david Hello! How are

you?” as shown below;

This message is received on other terminal of user ‘david’;

Now one message is sent from user ‘david’ to user ‘peter’;

This message is received on other terminal of user ‘peter’;

This process can continue and many more users can be added using different terminals.

THE END

You might also like