22PW03_DEC_WS1 (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

20XW68 DISTRIBUTED ENTERPRISE COMPUTING LAB

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])

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


client_socket.connect((server_ip, server_port))

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

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


server_socket.bind((server_ip, server_port))
server_socket.listen()

clients = []

def handle_client(client_socket, address):


print(f"Connection from {address} has been established!")
clients.append(client_socket)

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.")

def broadcast(message, client_socket):


for client in clients:
if client != client_socket:
try:
client.send(message.encode('utf-8'))
except:
client.close()
clients.remove(client)

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

# Configuration for FTP client


HOSTNAME = "127.0.0.1" # IP address of the FTP server
FTP_PORT = 2121 # Corrected port for FTP
USERNAME = "user"
PASSWORD = "pwd"
FILE_TO_UPLOAD = "dummy_file.txt"

# Ensure file exists or create it with dummy content


if not os.path.exists(FILE_TO_UPLOAD):
print(f"Creating dummy file: {FILE_TO_UPLOAD}")
with open(FILE_TO_UPLOAD, "w") as f:
f.write("This is a dummy file for FTP transfer.\n")
else:
print(f"Using existing file: {FILE_TO_UPLOAD}")

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()}")

# Upload the file


print(f"Uploading file: {FILE_TO_UPLOAD}...")
with open(FILE_TO_UPLOAD, "rb") as file:
ftp_server.storbinary(f"STOR {FILE_TO_UPLOAD}", file)

# List files on the server


print("Directory listing on the server:")
ftp_server.dir()

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

# Configuration for FTP server


FTP_PORT = 2121 # Default FTP port
FTP_USER = "user"
FTP_PASSWORD = "pwd"
FTP_DIRECTORY = "./ftp_storage" # Directory to store files

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')

# Set up handler and attach authorizer


handler = FTPHandler
handler.authorizer = authorizer
handler.banner = "pyftpdlib FTP server ready."

# Create and start the server


address = ('0.0.0.0', FTP_PORT) # Bind to the specified IP and port
server = FTPServer(address, handler)
server.max_cons = 256
server.max_cons_per_ip = 5
print(f"FTP server running on port {FTP_PORT}...")
server.serve_forever()

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

def start_client(server_ip, server_port):


client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((server_ip, server_port))

while True:
board_state = client_socket.recv(1024).decode()
print(board_state)

if "win" in board_state or "draw" in board_state:


break

move = input("Enter your move (1-9): ")


client_socket.sendall(move.encode())

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 make_move(self, position):


if self.board[position] == ' ':
self.board[position] = self.current_player
return True
return False

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()

print("Server started. Waiting for players...")

while True:
player_socket1, addr1 = server_socket.accept()
print(f"Player 1 connected from {addr1}")

player_socket2, addr2 = server_socket.accept()


print(f"Player 2 connected from {addr2}")

threading.Thread(target=handle_client, args=(player_socket1, player_socket2)).start()

if __name__ == "__main__":
start_server()

You might also like