package fr.umlv.ji.udp;
import java.net.*;
import java.io.*;
import java.util.logging.*;
public class MulticastDiscussion implements Runnable {
final static int MAX_DATA_SIZE = 64;
InetAddress address;
int port;
MulticastSocket socket;
public static void main(String[] args)
throws Exception {
if (args.length!=3) {
System.err.println("Usage: java fr.umlv.ji.udp.MulticastDiscussion "
+"addr port ttl");
return;
}
MulticastDiscussion discussion =
new MulticastDiscussion(InetAddress.getByName(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]));
discussion.start();
}
public MulticastDiscussion(InetAddress address, int port, int ttl)
throws IOException {
this.address = address;
this.port = port;
socket = new MulticastSocket(port);
socket.setTimeToLive(ttl);
socket.joinGroup(address);
}
public void start() throws IOException {
Thread t = new Thread(this);
t.setDaemon(true);
t.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String line;
byte[] buffer = new byte[0];
int len;
DatagramPacket datag = new DatagramPacket(buffer,0,address,port);
while ((line = reader.readLine()) != null) {
buffer = line.getBytes("8859_1");
for (int offset=0; offset<buffer.length; offset+=MAX_DATA_SIZE) {
len = Math.min(buffer.length-offset, MAX_DATA_SIZE);
datag.setData(buffer, offset, len);
socket.send(datag);
}
}
socket.leaveGroup(address);
socket.close();
}
public void run() {
try {
byte[] buffer = new byte[MAX_DATA_SIZE];
DatagramPacket datag = new DatagramPacket(buffer,buffer.length);
while (true) {
datag.setLength(MAX_DATA_SIZE);
socket.receive(datag);
System.out.println(datag.getAddress().getCanonicalHostName() +
" dit:\n\t" + new String(buffer,0, datag.getLength(),"8859_1"));
}
} catch (Exception e){
e.printStackTrace();
}
}
}