22PW03_DEC_WS1 (1)
22PW03_DEC_WS1 (1)
22PW03_DEC_WS1 (1)
Problem Sheet 1
1) A chat room is an interface that allows two or more people to chat and send messages
to everyone in the room. Set up a simple Chat Room server and allow multiple clients to
connect to it using Socket Programming .The server and clients processes should run on
different machines.
client.py
import socket
import threading
import sys
def send_messages(client_socket):
while True:
message = input("Enter : ")
print(f"{message=}")
if message.lower() == "exit":
break
client_socket.send(message.encode('utf-8'))
def receive_messages(client_socket):
while True:
try:
message = client_socket.recv(1024).decode('utf-8')
if message:
print(message)
else:
break
except:
print("An error occurred!")
break
# Client configuration
server_ip = sys.argv[1]
server_port = int(sys.argv[2])
threading.Thread(target=receive_messages, args=(client_socket,)).start()
send_messages(client_socket)
client_socket.close()
Server.py
import socket
import threading
server_ip = '0.0.0.0'
server_port = 12345
clients = []
while True:
try:
message = client_socket.recv(1024).decode('utf-8')
print(f"{message=}")
if message:
broadcast(message, client_socket)
else:
break
except:
break
client_socket.close()
clients.remove(client_socket)
print(f"Connection from {address} closed.")
while True:
client_socket, address = server_socket.accept()
threading.Thread(target=handle_client, args=(client_socket, address)).start()
2)Imagine a Client-Server architecture (As shown in Figure ), where user stores the file on
a server. The main server splits that file into two or more fragments and store each
fragment on separate storage server. When client retrieve the file from the main server,
the main server again retrieves the file in fragments from storage servers and present it
as a one file to user.
Client.py
import ftplib
import os
try:
print(f"Connecting to FTP server at {HOSTNAME} on port {FTP_PORT}...")
ftp_server = ftplib.FTP()
ftp_server.connect(HOSTNAME, FTP_PORT) # Connect to the FTP server at the right
address and port
ftp_server.login(USERNAME, PASSWORD) # Corrected login method
ftp_server.encoding = "utf-8"
print(f"Connected to FTP server: {ftp_server.getwelcome()}")
ftp_server.quit()
print("FTP session closed.")
except Exception as e:
print(f"An error occurred: {e}")
Server.py
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
import os
def main():
# Ensure the directory exists
if not os.path.exists(FTP_DIRECTORY):
print(f"Creating FTP directory: {FTP_DIRECTORY}")
os.makedirs(FTP_DIRECTORY)
else:
print(f"Using existing FTP directory: {FTP_DIRECTORY}")
# Set up authorizer
authorizer = DummyAuthorizer()
authorizer.add_user(FTP_USER, FTP_PASSWORD, FTP_DIRECTORY, perm='elradfmw')
if __name__ == '__main__':
main()
2) Develop a distributed tic-tac-toe game using multithreads and networking with socket
streams. A distributed tic-tac-toe game enables users to play on different machines from
anywhere .You need to develop a server for multiple clients. The server creates a server
socket and accepts connections from every two players to form a session. Each session
is a thread that communicates with the two players and determines the status of the
game. The server can establish any number of sessions. For each session, the first client
connecting to the server is identified as player 1 with token X, and the second client
connecting is identified as player 2 with token O. The server notifies the players of their
respective tokens. Once two clients are connected to it, the server starts a thread to
facilitate the game between the two players by performing the steps repeatedly, as shown
in Figure The server starts a thread to facilitate communications between the two players
is given in Figure.
Client
import socket
import sys
while True:
board_state = client_socket.recv(1024).decode()
print(board_state)
client_socket.close()
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python3 client.py <Server_IP> <Port_Number>")
sys.exit(1)
server_ip = sys.argv[1]
server_port = int(sys.argv[2])
start_client(server_ip, server_port)
Server.py
import socket
import threading
class TicTacToe:
def __init__(self):
self.board = [' ' for _ in range(9)] # 3x3 board
self.current_player = 'X' # Player X starts
def print_board(self):
print(f"{self.board[0]} | {self.board[1]} | {self.board[2]}")
print("--|---|--")
print(f"{self.board[3]} | {self.board[4]} | {self.board[5]}")
print("--|---|--")
print(f"{self.board[6]} | {self.board[7]} | {self.board[8]}")
def check_winner(self):
winning_combinations = [
(0, 1, 2), (3, 4, 5), (6, 7, 8), # Rows
(0, 3, 6), (1, 4, 7), (2, 5, 8), # Columns
(0, 4, 8), (2, 4, 6) # Diagonals
]
for a, b, c in winning_combinations:
if self.board[a] == self.board[b] == self.board[c] != ' ':
return True
return False
def is_full(self):
return ' ' not in self.board
def handle_client(player_socket1, player_socket2):
game = TicTacToe()
player_sockets = [player_socket1, player_socket2]
while True:
for player_socket in player_sockets:
player_socket.sendall(f"Current Board: {game.board}\n".encode())
if game.is_full():
for sock in player_sockets:
sock.sendall("It's a draw!\n".encode())
return
position = int(player_socket.recv(1024).decode()) - 1
if game.make_move(position):
if game.check_winner():
player_socket.sendall("You win!\n".encode())
other_player = player_sockets[1] if player_socket == player_sockets[0] else
player_sockets[0]
other_player.sendall("You lose!\n".encode())
return
else:
game.current_player = 'O' if game.current_player == 'X' else 'X'
else:
player_socket.sendall("Invalid move. Try again.\n".encode())
def start_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('0.0.0.0', 12345))
server_socket.listen()
while True:
player_socket1, addr1 = server_socket.accept()
print(f"Player 1 connected from {addr1}")
if __name__ == "__main__":
start_server()