+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

vijaygarg1init7910ba6

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