1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package net.grinder.communication;
23
24 import java.net.InetAddress;
25 import java.net.ServerSocket;
26 import java.net.Socket;
27 import java.net.UnknownHostException;
28
29
30
31
32
33 public final class SocketAcceptorThread extends Thread {
34
35 private final ServerSocket m_serverSocket;
36 private final int m_numberOfAccepts;
37 private Exception m_exception;
38 private Socket m_acceptedSocket;
39
40 public static SocketAcceptorThread create() throws Exception {
41 final SocketAcceptorThread acceptor = new SocketAcceptorThread(1);
42 acceptor.start();
43 return acceptor;
44 }
45
46 private SocketAcceptorThread(int numberOfAccepts) throws Exception {
47 m_serverSocket = new ServerSocket(0);
48 m_numberOfAccepts = numberOfAccepts;
49 }
50
51 public void run() {
52 try {
53 for (int i=0; i<m_numberOfAccepts; ++i) {
54 m_acceptedSocket = m_serverSocket.accept();
55 }
56 }
57 catch (Exception e) {
58 m_exception = e;
59 }
60 }
61
62 public String getHostName() throws UnknownHostException {
63 return InetAddress.getByName(null).getHostName();
64 }
65
66 public int getPort() {
67 return m_serverSocket.getLocalPort();
68 }
69
70 public Socket getAcceptedSocket() {
71 return m_acceptedSocket;
72 }
73
74 public final void close() throws Exception {
75
76 join();
77
78 if (m_exception != null) {
79 throw m_exception;
80 }
81
82 m_serverSocket.close();
83 }
84 }