Skip to content

Instantly share code, notes, and snippets.

@nikolajbaer
Created July 2, 2013 01:03
Show Gist options
  • Save nikolajbaer/5906027 to your computer and use it in GitHub Desktop.
Save nikolajbaer/5906027 to your computer and use it in GitHub Desktop.
Example of using Multicast socket to exchange datagrams
import java.net.MulticastSocket;
import java.lang.Thread;
import java.net.InetAddress;
import java.net.DatagramPacket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.UnknownHostException;
public class Client extends Thread {
private MulticastSocket sock;
private InetAddress group;
private int port;
public Client(InetAddress group,int port) throws IOException {
this.group = group;
this.port = port;
sock = new MulticastSocket(port);
sock.setTimeToLive(2);
sock.joinGroup(group);
}
public void run(){
System.out.println("Hi, I ("+this.getId()+") am listening!");
try{
while(true){
DatagramPacket d = new DatagramPacket(new byte[256],256);
sock.receive(d);
String result = new String(d.getData());
System.out.println(this.getId()+" received "+result);
}
}catch(IOException e){
System.err.println("Arrrrgh: "+e);
}
}
public void send(String msg) throws IOException {
byte[] data = msg.getBytes();
System.out.println(this.getId() + " sending "+data);
DatagramPacket d = new DatagramPacket(data,data.length,group,port);
sock.send(d);
}
public static void main(String[] args){
try{
int n = Integer.parseInt(args[0]);
Client[] clients = new Client[n];
InetAddress group = InetAddress.getByName("224.255.255.255");
for(int i=0; i<n;i++){
int port = 9001;
Client c = new Client(group,port);
c.start();
clients[i] = c;
}
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(true){
String x = in.readLine();
if(x=="exit"){ return; }
clients[0].send(x);
}
}catch(IOException e){ System.out.println("Argh: "+e); }
/*catch(UnknownHostException e){ System.out.println("Zounds: "+e); }*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment