Day Broadcast
import java.net.*;
import java.util.*;
public class DayBCast {
DatagramSocket ds;
DatagramPacket dp;
InetAddress addr;
public static final int DAYTIME_PORT = 5353;
public static void main(String args[]) throws Exception {
DayBCast db = new DayBCast(args[0]);
db.go();
}
public DayBCast(String target) throws Exception {
addr = InetAddress.getByName(target);
ds = new DatagramSocket();
}
public void go() throws Exception {
byte [] buff;
for (;;) {
Thread.sleep(1000);
System.out.println("Sending");
String s = (new Date()).toString();
buff = s.getBytes();
dp = new DatagramPacket(buff,buff.length,addr, DAYTIME_PORT);
ds.send(dp);
}
}
}
Day watch
import java.net.*;
public class DayWatch {
private DatagramSocket ds;
private DatagramPacket dp;
public static void main (String args[]) throws Exception {
DayWatch d = new DayWatch();
d.go();
}
public void go() throws Exception {
byte [] buff = new byte[64];
String s;
ds= new DatagramSocket(DayBCast.DAYTIME_PORT);
dp = new DatagramPacket(buff,buff.length);
for (;;) {
ds.receive(dp);
s = new String(dp.getData());
System.out.println("Time reçu de " + dp.getAddress() +
" est " + s);
}
}
}
Day Time Client
import java.io.*;
import java.net.*;
public class DayTimeClient{
public static final int port = 13;
public static void main(String args[])
{
Socket s = null;
String timestamp;
try
{
// <p> Création de la socket
s = new Socket(args[0], port);
// creation de l'imput stream
InputStream in = s.getInputStream();
BufferedReader bin =
new BufferedReader(new InputStreamReader(in));
// Informer l'utilisateur
System.out.println("Connecté à : " +
s.getInetAddress() + " port " + s.getPort()) ;
while (true) {
// lire le réseau
timestamp = bin.readLine();
if (timestamp == null) {
System.out.println("Connextion stopée");
break;
}
System.out.println("Daytime : " + timestamp);
}
}
catch (IOException e) { System.out.println(e);}
finally
{
//forcer la fermeture de la connexion
try
{ if (s != null) s.close(); }
catch (IOException e2)
{ }
}
}
}