0% found this document useful (0 votes)
22 views11 pages

Lab2 PDC

This document describes a lab assignment on client-server communication. The objectives are to understand client-server concepts and implement such communication. Students are asked to convert a basic client-server program into a group chat application using an event publish/subscribe model. A middleware would act as the chat group, allowing users to join and leave while broadcasting received messages to all connected users. Additionally, students must add unicast messaging capabilities to the middleware, allowing private messages to be sent to specific users rather than broadcasting to the whole group.

Uploaded by

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

Lab2 PDC

This document describes a lab assignment on client-server communication. The objectives are to understand client-server concepts and implement such communication. Students are asked to convert a basic client-server program into a group chat application using an event publish/subscribe model. A middleware would act as the chat group, allowing users to join and leave while broadcasting received messages to all connected users. Additionally, students must add unicast messaging capabilities to the middleware, allowing private messages to be sent to specific users rather than broadcasting to the whole group.

Uploaded by

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

Department of Computing

Course Code: CS432

Class: BSCS 11ABC

Lab 02: Client Server Communication

CLO4: Develop Distributed Applications/Systems

Date: February 12, 2024 and February 16, 2024

Instructors: Dr. Khurram Shahzad, Dr. Shah Khalid

NAME: MUHAMMAD ADEEL

CMS: 388064

SECTION: BSCS11A

CS332: Distributed Computing Page 1


Lab 02: Client Server Communication
Introduction

This lab focuses on the concepts of client server communication.

Objectives

To understand the concepts and implement client server communication..

Tools/Software Requirement

MS Visual Studio 2013

Description

By using simple network applications, we can send files or messages over the internet. A socket
is an object that symbolize a low-level connection point to the IP stack. This socket can be
opened or closed or one of a set amount of intermediate states. A socket can deliver and receive
data down this connection. Files is generally sent in blocks of a few kilobytes at a time for
effectiveness; each of these blocks is named as a packet. Here are the list of well-known port
numbers which usually used.

 Port 20, FTP Data


 Port 21, FTP Control
 Port 25, SMTP (email and outgoing)
 Port 53, DNS
 Port 80, HTTP (Web)

In this lab, we will explore the client server programming model in C#, however you are
free to choose any language for the lab task.

CS332: Distributed Computing Page 2


Consider Simple Client and SERVER programs in C#

Figure 1: CLIENT CODE

CS332: Distributed Computing Page 3


Figure 2: SERVER CODE

Lab Tasks

1. Your task is to use the above mentioned program and convert it to group chat using event
publish/subscribe architecture as discussed in class. Write a middleware that act as a chat
group. Users can join and leave that group. Middleware broadcast the received messages
to all the connected users.

Code:
Client:
import socket
import threading

class ChatClient:
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.username = None

CS332: Distributed Computing Page 4


def start(self):
self.username = input("Enter Your Name: ")
join_message = "JOIN " + self.username
self.sock.sendto(join_message.encode(), (self.host, self.port))

receive_thread = threading.Thread(target=self.receive_messages)
receive_thread.start()

print("Type your message or type 'exit' to leave:")


while True:
message = input()
if message.lower() == "exit":
leave_message = "LEAVE"
self.sock.sendto(leave_message.encode(), (self.host, self.port))
break
else:
message = self.username + " : " + message
self.sock.sendto(message.encode(), (self.host, self.port))

def receive_messages(self):
while True:
data, addr = self.sock.recvfrom(1024)
print(data.decode())

if __name__ == "__main__":

Middleware
import socket
import threading

class ChatGroupMiddleware:
def __init__(self, host, port):
self.host = host
self.port = port
self.users = []
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind((host, port))
self.lock = threading.Lock()

CS332: Distributed Computing Page 5


def start(self):
print("Middleware started, servicing on port", self.port)
while True:
data, addr = self.sock.recvfrom(1024)
message = data.decode()
if message.startswith("JOIN"):
self.handle_join(message, addr)
elif message.startswith("LEAVE"):
self.handle_leave(addr)
else:
self.broadcast(data)

def handle_join(self, message, addr):


username = message.split()[1]
with self.lock:
self.users.append((username, addr))
print(username, "joined the chat group.")

def handle_leave(self, addr):


with self.lock:
for user in self.users:
if user[1] == addr:
username = user[0]
self.users.remove(user)
print(username, "left the chat group.")
break

def broadcast(self, data):


with self.lock:
for user in self.users:
self.sock.sendto(data, user[1])

if __name__ == "__main__":
middleware = ChatGroupMiddleware("127.0.0.1", 2055)
middleware.start()

Output:
User1
CS332: Distributed Computing Page 6
User 2

User 3

Middleware

2. Add another feature in this middleware which is based on unicast i.e. message
send to particular user will not be received by all other users in the group. For this
you can assume the user ID of all users is well-known or middleware can provide
you that. Moreover, all the communication must be go through the middleware.

Code:

Middleware.py
import socket
import threading

CS332: Distributed Computing Page 7


class ChatGroupMiddleware:
def __init__(self, host, port):
self.host = host
self.port = port
self.users = {} # Dictionary to store user IDs and addresses
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind((host, port))
self.lock = threading.Lock()

def start(self):
print("Middleware started, servicing on port", self.port)
while True:
data, addr = self.sock.recvfrom(1024)
message = data.decode()
if message.startswith("JOIN"):
self.handle_join(message, addr)
elif message.startswith("LEAVE"):
self.handle_leave(addr)
else:
self.route_message(data)

def handle_join(self, message, addr):


username = message.split()[1]
user_id = message.split()[1] # Assuming user ID is provided by the
client
with self.lock:
self.users[user_id] = addr
print(username, "joined the chat group.")

def handle_leave(self, addr):


with self.lock:
for user_id, address in self.users.items():
if address == addr:
del self.users[user_id]
print("User with ID", user_id, "left the chat group.")
break

def route_message(self, data):


message = data.decode()
print("R: ", message)
sender, col, rec,msg = message.split(' ', 3)
# recipient_id, message = message.split(' ', 2)

CS332: Distributed Computing Page 8


recipient_address = self.users.get(rec)
message = sender + ' : '+ msg
if recipient_address:
self.sock.sendto(message.encode(), recipient_address)
elif rec.strip() == "all":
print(self.users)
for k,v in self.users.items():
self.sock.sendto(message.encode(), v)
else:
# u3 : 1 hey
print("User with ID", rec, "not found.")

if __name__ == "__main__":
middleware = ChatGroupMiddleware("127.0.0.1", 2055)
middleware.start()

Client.py:
import socket
import threading

class ChatClient:
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.username = None

def start(self):
self.username = input("Enter Your Name: ")
join_message = "JOIN " + self.username + " " + "id"
self.sock.sendto(join_message.encode(), (self.host, self.port))

receive_thread = threading.Thread(target=self.receive_messages)
receive_thread.start()

print("Type your message (to all) or 'unicast <user_id> <message>' to


send a private message:")
while True:
message = input()
if message.lower() == "exit":

CS332: Distributed Computing Page 9


leave_message = "LEAVE"
self.sock.sendto(leave_message.encode(), (self.host, self.port))
break
else:
self.send_message(message)

def receive_messages(self):
while True:
data, addr = self.sock.recvfrom(1024)
print(data.decode())

def send_message(self, message):


message = self.username + " : "+ message
self.sock.sendto(message.encode(), (self.host, self.port))

if __name__ == "__main__":
client = ChatClient("127.0.0.1", 2055)
client.start()

Output :
User 1

User 2

User 3

Middleware

CS332: Distributed Computing Page 10


Deliverables

Upload the project code files on LMS.

CS332: Distributed Computing Page 11

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy