+/EE360P

distributed systems

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

Wei-Lun Hungadd chap 6abf804d

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