+/EE360P
distributed systems
git clone https://git.julia.blue/+/EE360P
7910ba6
master
1package dist ; 2import java .util .*;import java .io .*; 3public class Linker implements MsgHandler { 4public int myId ; 5public int n ;// number of neighbors including myself 6final boolean debug =true ; 7Connector connector =null ; 8MsgHandler app =null ;// upper layer 9MsgHandler comm =null ;// lower layer 10public boolean appFinished =false ; 11public List <Integer >neighbors =new ArrayList <Integer >(); 12//public Properties prop = new Properties(); 13public Linker (String args [])throws Exception { 14String basename =args [0 ]; 15myId =Integer .parseInt (args [1 ]); 16if (!Topology .readNeighbors (myId ,neighbors )) 17Topology .setComplete (myId ,neighbors ,Integer .parseInt (args [2 ])); 18if (debug )System .out .println ("Neighbors are " +neighbors ); 19n =neighbors .size () +1 ; 20//prop.loadFromXML(new FileInputStream("LinkerProp.xml")); 21connector =new Connector (); 22connector .Connect (basename ,myId ,neighbors ); 23 } 24public void init (MsgHandler app ){ 25this .app =app ; 26for (int pid :neighbors ) 27 (new ListenerThread (pid ,this )).start (); 28 } 29public void sendMsg (int destId ,Object ...objects ) { 30int j =neighbors .indexOf (destId ); 31try { 32LinkedList <Object >objectList =Util .getLinkedList (objects ); 33ObjectOutputStream os =connector .dataOut [j ]; 34os .writeObject (Integer .valueOf (objectList .size ())); 35if (debug )System .out ."Sending to " +destId +":" ); 36for (Object object :objectList ) { 37os .writeObject (object ); 38if (debug )System .out .object +"," ); 39 } 40os .flush (); 41if (debug )System .out .println (); 42 }catch (IOException e ) {System .out .println (e );close (); } 43 } 44public Msg receiveMsg (int fromId ) { 45int i =neighbors .indexOf (fromId ); 46try { 47ObjectInputStream oi =connector .dataIn [i ]; 48int numItems = ((Integer )oi .readObject ()).intValue (); 49LinkedList <Object >recvdMessage =new LinkedList <Object >(); 50for (int j =0 ;j <numItems ;j ++) 51recvdMessage .add (oi .readObject ()); 52String tag = (String )recvdMessage .removeFirst (); 53return new Msg (fromId ,myId ,tag ,recvdMessage ); 54 }catch (Exception e ) {System .out .println (e ); 55close ();return null ; 56 } 57 58 } 59public synchronized void handleMsg (Msg m ,int src ,String tag ) {if (app !=null )app .handleMsg (m ,m .src ,m .tag ); 60 } 61// public synchronized void executeMsg(Msg m) { 62// if (m != null) 63// handleMsg(m, m.src, m.tag); 64// notifyAll(); 65// if (app != null) app.executeMsg(m); 66// } 67public synchronized int getMyId () {return myId ; } 68//public Properties getProp() { return prop;} 69public List <Integer >getNeighbors () {return neighbors ; } 70public void close () {appFinished =true ;connector .closeSockets (); } 71public void turnPassive () { } 72}