The Network
class handles all network operations.
The Network
object creates a limited number of worker
threads that run the network operations, so the number of concurrent
network connections is limited.
The queue
method
adds a network operation to a queue. The workers handle the network
operations from the queue in the order the operations are added.
public static void queue(final NetworkOperation op) { synchronized (queue) { queue.addElement(op); queue.notifyAll(); } synchronized (networkThreads) { for (int i = 0; i < networkThreads.length; i++) { if (networkThreads[i] == null) { networkThreads[i] = new Thread(new Network(), "NetworkThread" + i); networkThreads[i].start(); return; } } } }
The run
method tries to retrieve
an operation from the queue and send the corresponding network request.
If the queue is empty, the thread that calls this method waits for
the queue to fill again. The method is run by a worker thread when
the thread is started.
public final void run() { try { NetworkOperation op = null; while (true) { synchronized (queue) { if (queue.size() > 0) { op = (NetworkOperation) queue.elementAt(0); queue.removeElementAt(0); } else { queue.wait(); } } if (op != null) { try { switch (op.getMethod()) { case NetworkOperation.METHOD_POST: String response = sendHttpPost(op.getUrl(), op. getData(), op.getContentType()); op.networkHttpPostResponse(response); break; case NetworkOperation.METHOD_GET: default: byte[] data = sendHttpGet(op.getUrl()); op.networkHttpGetResponse(data); break; } } catch (NetworkException e) { switch (op.getMethod()) { case NetworkOperation.METHOD_POST: op.networkHttpPostResponse(null); break; case NetworkOperation.METHOD_GET: default: op.networkHttpGetResponse(null); break; } } } op = null; } } catch (Throwable t) { } }
The NetworkOperation
class is an abstract parent
class for all network operations.
The getMethod
method returns the HTTP connection method that the operation uses.
public int getMethod() { return METHOD_GET; }
Every operation has to provide a URL for the HTTP connection.
public abstract String getUrl();
If the POST method is used, the getData
method
provides the requested data.
public String getData() { return ""; }
If the POST method is used, the content type of
the requested data is provided by the getContentType
mehod.
public String getContentType() { return "application/x-www-form-urlencoded"; }
Subclasses of the NetworkOperation
class override the above methods as needed.