Professional Documents
Culture Documents
Experiment No. 7: Introduction of Multicast Socket Programming in Java Application
Experiment No. 7: Introduction of Multicast Socket Programming in Java Application
Experiment No. 7: Introduction of Multicast Socket Programming in Java Application
7
Introduction of Multicast socket Programming in Java Application
Multicasting in Java
1. Introduction
This article deals primarily with the subject of multicast communication in Java.
This sample code creates the socket and a datagram to send and then simply sends
the
DatagramPacketdgram;
InetAddress.getByName(MCAST_ADDR), DEST_PORT);
System.err.print(".");
socket.send(dgram);
Thread.sleep(1000);
One can use a normal DatagramSocket to send and receive multicast datagrams as
seen
MulticastSocket. The reason for this is simple, additional work needs to be done to
control and receive multicast traffic by all the protocol layers below UDP.
The example given below, opens a multicast socket, binds it to a specific port and
joins
MulticastSocket socket =
socket.joinGroup(InetAddress.getByName(MCAST_ADDR));
while(true) {
}
Experiment No. 8
A Program toimplement Multicast Socket Program in Java
1 Objective
• Learning Basics of Multicast Socket And Datagram Packet classes
of java.net packages
• Designing customized messages to send from one Machine or IP to
a group of Machine or IPs
• How to implement Multicast send data through Java Technology.
4 Solution
/*JAVA CODE */
import java.io.*;
public class QuoteServer {
public static void main(String[] args) throws IOException {
new QuoteServerThread().start();
}
}
The QuoteServerThread Class
The QuoteServerThread class implements the main logic of the quote
server:
import java.io.*;
import java.net.*;
import java.util.*;
public class QuoteServerThread extends Thread {
protected DatagramSocket socket = null;
protected BufferedReader in = null;
protected booleanmoreQuotes = true;
public QuoteServerThread() throws IOException {
this("QuoteServerThread");
}
public QuoteServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(4445);
try {
in = new BufferedReader(new FileReader("one-liners.txt"));
} catch (FileNotFoundException e) {
System.err.println("Could not open quote file. Serving time instead.");
}
}
public void run() {
while (moreQuotes) {
try {
byte[] buf = new byte[256];
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// figure out response
String dString = null;
if (in == null)
dString = new Date().toString();
else
dString = getNextQuote();
buf = dString.getBytes();