00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 package wttools.remotecons;
00024
00025 import wttools.remotecons.ifc.ConnectionHandlerIfc;
00026 import wttools.remotecons.ifc.LogIfc;
00027 import wttools.remotecons.ifc.CommandHandlerIfc;
00028 import java.net.Socket;
00029 import java.net.ServerSocket;
00030 import java.io.IOException;
00031 import java.util.List;
00032
00046 public class SocketListener extends Thread {
00047
00052 protected int port_no = Constants.DEFAULT_SERVER_PORT;
00059 protected ConnectionHandlerIfc conn_handler = null;
00064 protected List command_handlers = null;
00070 protected ServerSocket server_socket = null;
00077 protected LogIfc log_impl = null;
00082 protected boolean may_run = true;
00083
00087 public SocketListener() {}
00088
00095 public void startListening() throws IOException {
00096 startListening(Constants.DEFAULT_SERVER_PORT, true);
00097 }
00098
00107 public void startListening(int port_no, boolean daemon)
00108 throws IOException
00109 {
00110 may_run = true;
00111 this.port_no = port_no;
00112 server_socket = new ServerSocket(port_no);
00113 setDaemon(daemon);
00114 start();
00115 }
00116
00122 public void close() {
00123 may_run = false;
00124 try {
00125 server_socket.close();
00126 } catch (IOException e) {
00127
00128 }
00129 }
00130
00135 public void run() {
00136 while (may_run) {
00137 try {
00138 Socket socket = server_socket.accept();
00139 log("Connection request received.");
00140 log("Remote host is: "+socket.getInetAddress().getHostAddress());
00141 if (conn_handler != null) {
00142 conn_handler.handleNewConnection(socket, command_handlers);
00143 }
00144 else {
00145 log("Cant handle received connection request!");
00146 log("No connection handler defined.");
00147 }
00148 } catch (IOException e) {
00149 if (conn_handler != null) {
00150 conn_handler.handleException(e);
00151 }
00152 else {
00153 e.printStackTrace();
00154 }
00155 break;
00156 }
00157 }
00158 }
00159
00168 protected void log(String msg) {
00169 if (log_impl != null) {
00170 log_impl.log(msg);
00171 }
00172 }
00173
00179 public int getPort_no() {
00180 return this.port_no;
00181 }
00182
00188 public void setPort_no(int argPort_no){
00189 this.port_no = argPort_no;
00190 }
00191
00198 public ConnectionHandlerIfc getConn_handler() {
00199 return this.conn_handler;
00200 }
00201
00208 public void setConn_handler(ConnectionHandlerIfc argConn_handler){
00209 this.conn_handler = argConn_handler;
00210 }
00211
00217 public List getCommand_handlers() {
00218 return this.command_handlers;
00219 }
00220
00226 public void setCommand_handlers(List argCommand_handlers){
00227 this.command_handlers = argCommand_handlers;
00228 }
00229
00230 }
00231
00232
00233
00234
00235
00236
00237
00238
00239
00240
00241
00242
00243
00244
00245
00246
00247
00248
00249
00250
00251
00252
00253
00254