// // RobotAleatoire.java: Agent primitif pour le TP1 de ift6802 // Jean Vaucher 14 janv. 2004 // // Represente un "aspirateur" qui cherche de la poussiere dans les // chambres d'un hotel // - Voir description du TP1 // http://www.iro.umontreal.ca/~vaucher/ift6802/TP1.txt import java.io.*; import java.net.*; import java.util.*; public class RobotAleatoire { static Random rnd = new Random(); String sID ; int id = -1; int dir = 0; MulticastSocket multiSocket ; InetAddress multiAdr ; static int multiPort = 7777; DatagramSocket socket ; InetAddress localAdr ; int port ; public static void main(String[] args) throws IOException { if (args.length>0) multiPort = Integer.parseInt( args[0] ); new RobotAleatoire().init(); } void init() throws IOException { multiAdr = InetAddress.getByName("230.0.0.1"); multiSocket = new MulticastSocket( multiPort ); multiSocket.joinGroup( multiAdr ); localAdr = InetAddress.getLocalHost(); socket = new DatagramSocket(); port = socket.getLocalPort(); // Enregistrement DatagramPacket packet; String data = "allo," + localAdr.getHostName() + "," + port ; packet = new DatagramPacket(data.getBytes(), data.length(), multiAdr, multiPort); System.out.println("Agent signing in"); socket.send(packet); new Slave1() . start(); System.out.println(" Agent waits for query"); while (true) { try { byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); try { socket.receive(packet); } catch (IOException e) {} data = new String(packet.getData(),0,packet.getLength()); System.out.println("Recoit: " + data); StringTokenizer st = new StringTokenizer( data, "," ); String rep = st.nextToken(); sID = st.nextToken(); String orig = st.nextToken(); if (rep.equals("bang")) continue; String env = st.nextToken(); if (id < 0) { id = Integer.parseInt( sID ) ; System.out.println("Agent enregistre: " + id); } // Trouver prochaine direction dir = findMove(env); data = "go,0," + id + "," + dir; buf = data.getBytes(); DatagramPacket p2 = new DatagramPacket(buf, buf.length, packet.getAddress(), packet.getPort()); socket.send(p2); System.out.println( " Agent"+ id + " repond " + data); } catch (IOException e) { System.out.println("Probleme: " + e ); } } } int findMove (String s) { return rnd.nextInt(9); } class Slave1 extends Thread { public void run() { DatagramPacket packet; while (true) { try { byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); multiSocket.receive(packet); String received = new String(packet.getData(),0,packet.getLength()); System.out.println("Multicast: " + received); } catch (IOException e) { System.out.println("Probleme: " + e ); } } } } } // --- end Hotel Agent ----