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 = [Link]('user_database.db')
cursor = [Link]()
[Link]('''
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
password TEXT
)
''')
[Link]()
[Link]()
# Function to check user credentials in the database
def check_credentials(username, password):
conn = [Link]('user_database.db')
cursor = [Link]()
[Link]('SELECT * FROM users WHERE username = ? AND password = ?',
(username, password))
result = [Link]()
[Link]()
return result is not None
# Function to add a new user to the database
def add_user(username, password):
conn = [Link]('user_database.db')
cursor = [Link]()
[Link]('INSERT INTO users (username, password) VALUES (?, ?)',
(username, password))
[Link]()
[Link]()
# 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 = [Link]()
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 = [Link](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 = [Link](target=handle_client,
args=(client_socket, address))
client_handler.start()
Source Code for Client
import socket
# Create a TCP/IP socket
client_socket = [Link](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 [Link]() == '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([Link]())
if [Link]().startswith("list"):
online_users = client_socket.recv(1024).decode()
print(online_users)
elif [Link]().startswith("send"):
client_socket.send([Link]())
send_status = client_socket.recv(1024).decode()
print(send_status)
else:
print("Invalid option entered!")
continue
break
elif [Link]() == '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