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       * @param serverSocket server socket delegate
35       */
36      public ServerSocketListener(ServerSocket serverSocket) {
37          this.serverSocket = serverSocket;
38      }
39  
40      /**
41       * {@inheritDoc}
42       */
43      public T acceptClient() throws IOException {
44          Socket socket = serverSocket.accept();
45          return createClient(socketAddressToString(socket.getRemoteSocketAddress()), socket);
46      }
47  
48      /**
49       * Creates the client object for a new socket connection
50       * @param id identifier string for the client
51       * @param socket client's socket connection
52       * @return client object
53       * @throws IOException
54       */
55      protected abstract T createClient(String id, Socket socket) throws IOException;
56  
57      /**
58       * {@inheritDoc}
59       */
60      public void close() {
61          CloseUtil.closeQuietly(serverSocket);
62      }
63  
64      /**
65       * {@inheritDoc}
66       */
67      @Override
68      public String toString() {
69          return socketAddressToString(serverSocket.getLocalSocketAddress());
70      }
71  
72      /**
73       * Converts a socket address to a reasonable display string.
74       * @param address the subject socket address
75       * @return display string
76       */
77      private String socketAddressToString(SocketAddress address) {
78          String addr = address.toString();
79          int i = addr.indexOf("/");
80          if (i >= 0) {
81              addr = addr.substring(i + 1);
82          }
83          return addr;
84      }
85  
86  }