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