Hello all, I was wondering whether it is possible for a class implementing runnable, to notify another class through Observable ?? I mean i have tried it and end up with two non responding program. can somebody point it out whether it is possible at al.l if possible what i am doing wrong here ? Regards.
Server side code
import java.io.* ; import java.net.* ; import java.util.* ; class Client implements Runnable{ Socket s = null ; ObjectInputStream in = null ; ObjectOutputStream out = null ; public Client(Socket s){ try{ this.s = s ; in = new ObjectInputStream(s.getInputStream()) ; out = new ObjectOutputStream(s.getOutputStream()) ; } catch (Exception e){ System.out.println(e) ; } } public void run(){ System.out.println(s) ; try{ Random r = new Random() ; for (int i = 0 ; i < 1000000 ; i++){ System.out.println(i) ; //int rd = r.nextInt() % 200 ; if (i % 1000 == 0){ out.writeObject(new String("muchacha " + i)) ; out.flush() ; }else{ out.writeObject(new Integer(i)) ; out.flush() ; } } out.close() ; in.close() ; s.close() ; } catch (Exception e){ System.out.println(e) ; } } } class Server{ public static void main(String [] args){ ServerSocket ss = null ; Socket conn = null ; try{ ss = new ServerSocket(4444) ; while (true){ conn = ss.accept() ; System.out.println("Connection from " + conn) ; Thread t = new Thread(new Client(conn)) ; t.start() ; } } catch (Exception e){} } }
Client side code
import java.util.* ; import java.net.* ; import java.io.* ; class Watcher implements Observer{ public void update(Observable obj, Object arg){ System.out.println("observer update() arg : " + arg) ; } } class BeingWatched extends Observable implements Runnable{ Socket conn = null ; ObjectInputStream in = null ; ObjectOutputStream out = null ; public BeingWatched(Socket conn, Observer w){ try{ this.addObserver(w) ; this.conn = conn ; } catch (Exception e){} } public void run(){ System.out.println("came here") ; try{ in = new ObjectInputStream(conn.getInputStream()) ; out = new ObjectOutputStream(conn.getOutputStream()) ; while(true){ Object o = (Object)in.readObject() ; if (o instanceof String){ setChanged() ; notifyObservers(o) ; } }}catch(Exception e){ System.out.println(e) ;} } } class Obs{ public static void main(String [] args){ try{ Watcher w1 = new Watcher() ; Socket s = new Socket("127.0.0.1", 4444) ; BeingWatched bw = new BeingWatched(s, w1) ; Thread t = new Thread (bw) ; t.start() ; } catch(Exception e){} } }