View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.net.server;
15  
16  import java.io.IOException;
17  import java.net.ServerSocket;
18  import java.net.Socket;
19  import java.net.SocketAddress;
20  
21  import ch.qos.logback.core.util.CloseUtil;
22  
23  /**
24   * A {@link ServerListener} that accepts connections on a {@link ServerSocket}.
25   *
26   * @author Carl Harris
27   */
28  public abstract class ServerSocketListener<T extends Client> implements ServerListener<T> {
29  
30      private final ServerSocket serverSocket;
31  
32      /**
33       * Constructs a new listener.
34       * 
35       * @param serverSocket server socket delegate
36       */
37      public ServerSocketListener(ServerSocket serverSocket) {
38          this.serverSocket = serverSocket;
39      }
40  
41      /**
42       * {@inheritDoc}
43       */
44      public T acceptClient() throws IOException {
45          Socket socket = serverSocket.accept();
46          return createClient(socketAddressToString(socket.getRemoteSocketAddress()), socket);
47      }
48  
49      /**
50       * Creates the client object for a new socket connection
51       * 
52       * @param id     identifier string for the client
53       * @param socket client's socket connection
54       * @return client object
55       * @throws IOException
56       */
57      protected abstract T createClient(String id, Socket socket) throws IOException;
58  
59      /**
60       * {@inheritDoc}
61       */
62      public void close() {
63          CloseUtil.closeQuietly(serverSocket);
64      }
65  
66      /**
67       * {@inheritDoc}
68       */
69      @Override
70      public String toString() {
71          return socketAddressToString(serverSocket.getLocalSocketAddress());
72      }
73  
74      /**
75       * Converts a socket address to a reasonable display string.
76       * 
77       * @param address the subject socket address
78       * @return display string
79       */
80      private String socketAddressToString(SocketAddress address) {
81          String addr = address.toString();
82          int i = addr.indexOf("/");
83          if (i >= 0) {
84              addr = addr.substring(i + 1);
85          }
86          return addr;
87      }
88  
89  }