+/EE360P

distributed systems

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

Wei-Lun Hungadd chap 6abf804d

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