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

61FIT3NPR - W09 Tut Multicast Socket New

Uploaded by

Uyên Tú
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)
15 views5 pages

61FIT3NPR - W09 Tut Multicast Socket New

Uploaded by

Uyên Tú
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/ 5

Faculty of Information Technology

HANOI UNIVERSITY

61FIT3NPR – Network Programming


Tutorial week 09
Java Multicast Sockets
1. Multicast communication by MulticastSocket
UDPMulticastClient.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class UDPMulticastClient implements Runnable {

public static void main(String[] args) {


Thread t=new Thread(new UDPMulticastClient());
t.start();
}

public void receiveUDPMessage(String ip, int port) throws IOException {


byte[] buffer=new byte[1024];
MulticastSocket socket=new MulticastSocket(4321);
InetAddress group=InetAddress.getByName("230.0.0.0");
socket.joinGroup(group);
System.out.println("Waiting for multicast message...");
int n=1;
while(true){
DatagramPacket packet=new DatagramPacket(buffer,
buffer.length);
socket.receive(packet);
String msg=new
String(packet.getData(),packet.getOffset(),packet.getLength());
System.out.println("[Multicast UDP message received] "+n+":
"+msg);
n++;
if("OK".equals(msg)) {
System.out.println("No more message. Exiting : "+msg);
break;
}
}
socket.leaveGroup(group);
socket.close();
}

@Override
public void run(){
try {
receiveUDPMessage("230.0.0.0", 4321);
}catch(IOException ex){
ex.printStackTrace();
}
}
}
UDPMulticastPublisher.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPMulticastPublisher {

public static void sendUDPMessage(String message,String ipAddress, int


port) throws IOException {
DatagramSocket socket = new DatagramSocket();
InetAddress group = InetAddress.getByName(ipAddress);
byte[] msg = message.getBytes();
DatagramPacket packet = new DatagramPacket(msg, msg.length,group,
port);
socket.send(packet);
socket.close();
}

public static void main(String[] args) throws IOException {


int n = 1;
while(true) {
String s = "Hi there! This is a multicast message number ";

s = s + Integer.toString(n) + " from publisher!";


n++;
sendUDPMessage(s, "230.0.0.0",4321);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//sendUDPMessage("This is the second multicast
message","230.0.0.0", 4321);
//sendUDPMessage("This is the third multicast
message","230.0.0.0", 4321);
//sendUDPMessage("OFF", "230.0.0.0", 4321);

}
}
}

Compile and run :


2. Multicasting through Datagram Channels

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.lang.Thread;
public class MulticastPublisher {
private static final String MULTICAST_INTERFACE = "en0";
private static final int MULTICAST_PORT = 4567;
private static final String MULTICAST_IP = "230.0.0.0";
//int n=1;
public void sendMessage(String ip, String iface, int port,String message)
throws IOException {
DatagramChannel datagramChannel=DatagramChannel.open();
datagramChannel.bind(null);
NetworkInterface networkInterface=NetworkInterface.getByName(iface);

datagramChannel.setOption(StandardSocketOptions.IP_MULTICAST_IF,networkInterfa
ce);
ByteBuffer byteBuffer=ByteBuffer.wrap(message.getBytes());
InetSocketAddress inetSocketAddress=new InetSocketAddress(ip,port);
datagramChannel.send(byteBuffer,inetSocketAddress);
}
public static void main(String[] args) throws IOException {
MulticastPublisher mp=new MulticastPublisher();
int n = 1;
while(true) {
String s = "Hi there! This is the message number ";

s = s + Integer.toString(n) + " from publisher!";


System.out.println(s);
mp.sendMessage(MULTICAST_IP,MULTICAST_INTERFACE,MULTICAST_PORT,s);
n++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}

import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.MembershipKey;

public class MulticastReceiver {


private static final String MULTICAST_INTERFACE = "en0";
private static final int MULTICAST_PORT = 4567;
private static final String MULTICAST_IP = "230.0.0.0";

private String receiveMessage(String ip, String iface, int port) throws


IOException {

DatagramChannel datagramChannel = DatagramChannel


.open(StandardProtocolFamily.INET);
NetworkInterface networkInterface = NetworkInterface
.getByName(iface);
datagramChannel.setOption(StandardSocketOptions
.SO_REUSEADDR, true);
datagramChannel.bind(new InetSocketAddress(port));
datagramChannel.setOption(StandardSocketOptions
.IP_MULTICAST_IF, networkInterface);
InetAddress inetAddress = InetAddress.getByName(ip);
MembershipKey membershipKey = datagramChannel.join
(inetAddress, networkInterface);
System.out.println("Waiting for the message...");
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
datagramChannel.receive(byteBuffer);
byteBuffer.flip();
byte[] bytes = new byte[byteBuffer.limit()];
byteBuffer.get(bytes, 0, byteBuffer.limit());
membershipKey.drop();
return new String(bytes);
}
public static void main(String[] args) throws IOException {
int n=1;
while(true) {
MulticastReceiver mr = new MulticastReceiver();
System.out.println("Message received : "+n+" "+
mr.receiveMessage(MULTICAST_IP,MULTICAST_INTERFACE,MULTICAST_PORT));
n++;
}
}
}
To find the name of network interface used, you can try the following codes:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;

public class ListNets {

public static void main(String args[]) throws SocketException {


Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}

static void displayInterfaceInformation(NetworkInterface netint) throws


SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}
}

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