Skip to content

Instantly share code, notes, and snippets.

@bubunyo
Created September 25, 2015 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bubunyo/ed800ae67d954066956b to your computer and use it in GitHub Desktop.
Save bubunyo/ed800ae67d954066956b to your computer and use it in GitHub Desktop.
package multicast;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class MulticastSocketClient {
final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8880;
static MulticastSocket clientSocket;
static byte[] buf = new byte[256];
static InetAddress addr;
public static void main(String[] args) throws UnknownHostException {
// Get the address that we are going to connect to.
// InetAddress address = InetAddress.getByName(INET_ADDR);
// Create a buffer of bytes, which will be used to store
// the incoming bytes containing the information from the server.
// Since the message is small here, 256 bytes should be enough.
// Create a new Multicast socket (that will allow other sockets/programs
// to join it as well.
addr = InetAddress.getByName(INET_ADDR);
try {
clientSocket = new MulticastSocket(PORT);
new InputThread().start();
//Joint the Multicast group.
clientSocket.joinGroup(addr);
while (true) {
// Receive the information and print it.
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
clientSocket.receive(msgPacket);
String msg = new String(buf, 0, buf.length);
System.out.println(msg);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
static class InputThread extends Thread {
@Override
public void run() {
super.run();
Scanner scanner = new Scanner(System.in);
while (true)
if (scanner.hasNext()) {
try {
String msg = scanner.next();
DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
msg.getBytes().length, addr, PORT);
clientSocket.send(msgPacket);
System.out.print(">>");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment