+/EE360P

distributed systems

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

vijaygarg1init6bd33a4

master
2.1 KiB63 linesraw
1package dist;
2import java.util.*;import java.net.*;import java.io.*;
3import name.*;
4public class Connector {
5	ServerSocket listener; Socket[] link;
6	public ObjectInputStream[] dataIn;
7	public ObjectOutputStream[] dataOut;
8	Name myNameclient;
9	public void Connect(String basename, int myId, List<Integer> neighbors)
10			throws Exception {
11		myNameclient = new Name();
12		int numNeigh = neighbors.size();
13		link = new Socket[numNeigh];
14		dataIn = new ObjectInputStream[numNeigh];
15		dataOut = new ObjectOutputStream[numNeigh];
16		int localport = getLocalPort(myId);
17		listener = new ServerSocket(localport);
18		
19		/* register my name in the name server */
20		myNameclient.insertName(basename + myId, (InetAddress.getLocalHost())
21				.getHostName(), localport);
22		
23		/* accept connections from all the smaller processes */
24		for (int pid : neighbors) {
25			if (pid  < myId) {
26				Socket s = listener.accept();
27				InputStream is = s.getInputStream();
28				ObjectInputStream din = new ObjectInputStream(is);
29				Integer hisId = (Integer) din.readObject();
30				int i = neighbors.indexOf(hisId);
31				String tag = (String) din.readObject();
32				if (tag.equals("hello")) {
33					link[i] = s;
34					dataIn[i] = din;
35					dataOut[i] = new ObjectOutputStream(
36							s.getOutputStream()); }
37			}
38		}
39		/* contact all the bigger processes */
40		for (Integer pid : neighbors) {
41			if (pid > myId) {
42				InetSocketAddress addr = myNameclient.searchName(
43							basename + pid, true);
44				int i = neighbors.indexOf(pid);
45				link[i] = new Socket(addr.getHostName(), addr.getPort());
46				dataOut[i] = new 
47					ObjectOutputStream(link[i].getOutputStream());
48				/* send a hello message to P_i */
49				dataOut[i].writeObject(new Integer(myId));
50				dataOut[i].writeObject(new String("hello"));
51				dataOut[i].flush();
52				dataIn[i]=new ObjectInputStream(link[i].getInputStream());}	
53		}
54	}
55	int getLocalPort(int id) {return Symbols.ServerPort + 20 + id;	}
56	public void closeSockets() {
57		try {
58			listener.close();
59			for (Socket s : link) s.close();
60			myNameclient.clear();
61		} catch (Exception e) { System.err.println(e); }
62	}
63}