1 package org.vamsas.client.picking;
\r
6 public class PickManager
\r
8 // Maintains a list of client communication objects - each object represents
\r
9 // a way of talking to either:
\r
10 // the server - if this is client side (and in which case, the list will only contain one element
\r
11 // the other clients - if this is server side
\r
12 private LinkedList clients;
\r
14 private PickServer server;
\r
16 public PickManager()
\r
18 server = new PickServer(this);
\r
19 clients = new LinkedList();
\r
21 new InitializeThread().start();
\r
24 // Called whenver we try to make a new endpoint<->endpoint connection
\r
25 boolean addClientConnection(Socket socket)
\r
27 PickEndPoint client = new PickEndPoint(this, socket);
\r
29 if (client.openConnection())
\r
31 clients.add(client);
\r
32 System.out.println("List now contains " + clients.size() + " client(s)");
\r
39 public void sendMessage(String str)
\r
41 forwardMessage(null, str);
\r
44 // Forwards (or sends) a message
\r
45 // When the server receives a message, it will be resent to all clients,
\r
46 // but *not* to the client that sent it out in the first place!
\r
47 private void forwardMessage(PickEndPoint origin, String str)
\r
49 ListIterator itor = clients.listIterator();
\r
50 while (itor.hasNext())
\r
52 PickEndPoint client = (PickEndPoint) itor.next();
\r
54 if (client != origin)
\r
59 // Called by the endpoint code when a message is received
\r
60 // The manager has to:
\r
61 // a) hand message to VAMSAS app
\r
62 // b) forward it to other clients if we're the server
\r
63 void handleMessage(PickEndPoint origin, String str)
\r
65 if (server.isServer())
\r
66 forwardMessage(origin, str);
\r
68 // TODO: pass message to VAMSAS API
\r
71 void removeEndPoint(PickEndPoint client)
\r
73 clients.remove(client);
\r
74 System.out.println("List now contains " + clients.size() + " client(s)");
\r
76 // If there's no endpoints left, then we've lost all connections and
\r
77 // need to reinitialize
\r
78 if (clients.size() == 0)
\r
79 new InitializeThread().start();
\r
82 private class InitializeThread extends Thread
\r
86 System.out.println("Initializing connection...");
\r
87 boolean connected = false;
\r
89 // Loop until we can get a connection (one way or the other)
\r
92 // Sleep for a rnd time so we don't end up with all the VAMSAS
\r
93 // apps trying to initialize servers at the same time
\r
94 try { Thread.sleep((int)Math.random()); }
\r
95 catch (InterruptedException e) {}
\r
97 // Attempt to open the server port...
\r
98 if (server.isServer() || server.createServer())
\r
101 // If it fails, then attempt to make a client connection...
\r
102 else if (addClientConnection(null))
\r