1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.net.telnet;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.OutputStream;
22 import java.net.ServerSocket;
23 import java.net.Socket;
24
25
26
27
28 public class TelnetTestSimpleServer implements Runnable {
29 ServerSocket serverSocket;
30 Socket clientSocket;
31 Thread listener;
32
33
34
35
36
37
38
39
40 public TelnetTestSimpleServer(final int port) throws IOException {
41 serverSocket = new ServerSocket(port);
42
43 listener = new Thread(this);
44
45 listener.start();
46 }
47
48 public void disconnect() {
49 if (clientSocket == null) {
50 return;
51 }
52 synchronized (clientSocket) {
53 try {
54 clientSocket.notify();
55 } catch (final Exception e) {
56 System.err.println("Exception in notify, " + e.getMessage());
57 }
58 }
59 }
60
61 public InputStream getInputStream() throws IOException {
62 if (clientSocket != null) {
63 return clientSocket.getInputStream();
64 }
65 return null;
66 }
67
68 public OutputStream getOutputStream() throws IOException {
69 if (clientSocket != null) {
70 return clientSocket.getOutputStream();
71 }
72 return null;
73 }
74
75 @Override
76 public void run() {
77 boolean bError = false;
78 while (!bError) {
79 try {
80 clientSocket = serverSocket.accept();
81 synchronized (clientSocket) {
82 try {
83 clientSocket.wait();
84 } catch (final Exception e) {
85 System.err.println("Exception in wait, " + e.getMessage());
86 }
87 try {
88 clientSocket.close();
89 } catch (final Exception e) {
90 System.err.println("Exception in close, " + e.getMessage());
91 }
92 }
93 } catch (final IOException e) {
94 bError = true;
95 }
96 }
97
98 try {
99 serverSocket.close();
100 } catch (final Exception e) {
101 System.err.println("Exception in close, " + e.getMessage());
102 }
103 }
104
105 public void stop() {
106 listener.interrupt();
107 try {
108 serverSocket.close();
109 } catch (final Exception e) {
110 System.err.println("Exception in close, " + e.getMessage());
111 }
112 }
113 }