0% found this document useful (0 votes)
3 views5 pages

DC Lab Programs 6 10

The document outlines an experiment on Group Communication using Socket Programming, detailing the theory behind it, including concepts like multicast, client management, and thread safety. It provides a Java and Python implementation of a group chat server and client, demonstrating how clients can communicate in real-time while managing connections and disconnections. The server broadcasts messages to all clients, ensuring full-duplex communication and maintaining awareness of user presence in the chat.

Uploaded by

abhisheknaik2k20
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)
3 views5 pages

DC Lab Programs 6 10

The document outlines an experiment on Group Communication using Socket Programming, detailing the theory behind it, including concepts like multicast, client management, and thread safety. It provides a Java and Python implementation of a group chat server and client, demonstrating how clients can communicate in real-time while managing connections and disconnections. The server broadcasts messages to all clients, ensuring full-duplex communication and maintaining awareness of user presence in the chat.

Uploaded by

abhisheknaik2k20
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

Abhishek Naik C12 Group: 21 2203118

Experiment 2: Group Communication

AIM
Write a program to implement Group Communication using Socket Programming.
THEORY
Group Communication extends basic Interprocess Communication (IPC) by enabling multiple processes to
communicate simultaneously within a defined group. It is a core concept in distributed systems, supporting
collaborative applications such as chat systems, multiplayer games, and distributed computing frameworks.

Key Concepts:
• Multicast / Broadcast:
o Broadcast: Message is sent to all connected clients in the system.
o Multicast: Message is sent to a specific subset (group) of clients.
This improves efficiency compared to sending individual messages to each client.
• Client List Management:
The server maintains a dynamic collection (e.g., ArrayList, ConcurrentHashMap) of all connected clients
along with their output streams for message delivery.
• Thread Safety:
Since multiple threads (one per client) access the shared client list, synchronization mechanisms like:
o synchronized blocks
o ReentrantLock
o Concurrent collections
are used to prevent race conditions and ensure data consistency.
• Membership Events:
o Join Event: When a new client connects, all existing clients are notified.
o Leave Event: When a client disconnects, the server informs the group.
This helps maintain awareness among participants.
• Full-Duplex Communication:
Clients can send and receive messages simultaneously using separate threads (one for sending, one for
receiving).
• Message Tagging:
Messages are often tagged with sender ID, timestamp, or username to identify the source.

Working Principle:
1. The server starts and listens for incoming client connections.
2. When a client connects:
o A new handler thread is created.
o The client is added to the shared client list.
o A “user joined” message is broadcast to all clients.
3. Each client:
o Uses one thread to send messages to the server.
o Uses another thread to continuously listen for incoming messages.
Abhishek Naik C12 Group: 21 2203118

4. When a client sends a message:


o The server receives it via the client’s handler thread.
o The broadcast() method is invoked.
o The message is forwarded to all connected clients except the sender (or including sender,
depending on design).
5. When a client disconnects:
o It is removed from the client list.
o A “user left” message is broadcast to remaining clients.
6. The system continues running, supporting dynamic joins and leaves.

FLOWCHART
Abhishek Naik C12 Group: 21 2203118

Java Implementation
Server: [Link]
// Exp-2: Group Communication - Server (Java) import
[Link].*; import [Link].*; import [Link].*; public class
GroupChatServer {
static List<PrintWriter> clients = new ArrayList<>(); public static
void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5001);
[Link]("Group Chat Server is running...");
while (true) new Thread(new ClientHandler([Link]())).start();
}
static synchronized void broadcast(String msg, PrintWriter sender) { for
(PrintWriter c : clients) if (c != sender) [Link](msg);
}
static class ClientHandler implements Runnable { Socket
socket; PrintWriter out; String name; ClientHandler(Socket s)
{ socket = s; } public void run() { try (BufferedReader in
= new BufferedReader(new
InputStreamReader([Link]()))) {
out = new PrintWriter([Link](), true); [Link]("Enter
your name:"); name = [Link](); synchronized ([Link]) {
[Link](out); }
broadcast(name + " has joined the chat.", out); String
msg; while ((msg = [Link]()) != null) { if
([Link]("exit")) break; broadcast(name + ":
" + msg, out);
}
} catch (IOException e) {}
synchronized ([Link]) { [Link](out); } broadcast(name + " has
left the chat.", out);
}
}
}

Client: [Link]
// Exp-2: Group Communication - Client (Java)
import [Link].*; import [Link].*; import [Link]; public
class GroupChatClient { public static void main(String[] args) throws
IOException {
Socket socket = new Socket("localhost", 5001);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true); new
Thread(() -> { try { String m; while ((m=[Link]())!=null)
[Link](m); } catch(Exception e){} }).start();
Scanner sc = new Scanner([Link]);
Abhishek Naik C12 Group: 21 2203118

while ([Link]()) {
String msg = [Link](); [Link](msg); if
([Link]("exit")) break;
}
[Link]();
}
}

Python Implementation
Server: group_chat_server.py # Exp-2: Group
Communication - Server (Python) import socket,
threading clients = {}; lock = [Link]() def
broadcast(msg, sender=None):
with lock: for s in list(clients): if s !=
sender: try: [Link]((msg+'\n').encode())
except: pass def handle_client(conn, addr):
[Link]("Enter your name:\n".encode()) name =
[Link](1024).decode().strip() with lock:
clients[conn] = name broadcast(f"{name} has joined
the chat.", conn) try: while True:
data = [Link](1024).decode().strip() if not
data or [Link]() == 'exit': break broadcast(f"{name}:
{data}", conn) finally:
with lock: [Link](conn, None) broadcast(f"{name} has left the
chat.", conn); [Link]() def main(): server =
[Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
[Link](('[Link]', 5001)); [Link](10) print("Group Chat Server is
running...") while True:
conn, addr = [Link]() print(f"New client connected: {addr}")
[Link](target=handle_client, args=(conn,addr), daemon=True).start() if __name__ ==
"__main__": main()

Client: group_chat_client.py
# Exp-2: Group Communication - Client (Python)
import socket,
threading def recv(c):
while True:
try: print([Link](1024).decode(), end='')
except: break def main():
c = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](('localhost', 5001)) [Link](target=recv, args=(c,),
daemon=True).start() while True:
msg = input()
Abhishek Naik C12 Group: 21 2203118

[Link]([Link]()) if [Link]().lower()
== 'exit': break [Link]() if __name__ ==
"__main__": main()

You might also like