01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03: package fitnesse.socketservice;
04:
05: import java.io.IOException;
06: import java.net.ServerSocket;
07: import java.net.Socket;
08: import java.util.LinkedList;
09:
10: public class SocketService {
11: private ServerSocket serverSocket = null;
12:
13: private Thread serviceThread = null;
14:
15: private boolean running = false;
16:
17: public SocketServer server = null;
18:
19: public LinkedList threads = new LinkedList();
20:
21: public SocketService(int port, SocketServer server)
22: throws Exception {
23: this .server = server;
24: serverSocket = new ServerSocket(port);
25: serviceThread = new Thread(new Runnable() {
26: public void run() {
27: serviceThread();
28: }
29: });
30: serviceThread.start();
31: }
32:
33: public void close() throws Exception {
34: waitForServiceThreadToStart();
35: running = false;
36: serverSocket.close();
37: serviceThread.join();
38: waitForServerThreads();
39: }
40:
41: private void waitForServiceThreadToStart() {
42: while (running == false)
43: Thread.yield();
44: }
45:
46: void serviceThread() {
47: running = true;
48: while (running) {
49: try {
50: Socket s = serverSocket.accept();
51: startServerThread(s);
52: } catch (IOException e) {
53: }
54: }
55: }
56:
57: private void startServerThread(Socket s) {
58: Thread serverThread = new Thread(new ServerRunner(s));
59: synchronized (threads) {
60: threads.add(serverThread);
61: }
62: serverThread.start();
63: }
64:
65: private void waitForServerThreads() throws InterruptedException {
66: while (threads.size() > 0) {
67: Thread t;
68: synchronized (threads) {
69: t = (Thread) threads.getFirst();
70: }
71: t.join();
72: }
73: }
74:
75: private class ServerRunner implements Runnable {
76: private Socket socket;
77:
78: ServerRunner(Socket s) {
79: socket = s;
80: }
81:
82: public void run() {
83: try {
84: server.serve(socket);
85: synchronized (threads) {
86: threads.remove(Thread.currentThread());
87: }
88: } catch (Exception e) {
89: }
90: }
91: }
92: }
|