001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.net.server;
015
016import java.io.IOException;
017import java.net.ServerSocket;
018import java.net.Socket;
019import java.net.SocketAddress;
020
021import ch.qos.logback.core.util.CloseUtil;
022
023/**
024 * A {@link ServerListener} that accepts connections on a {@link ServerSocket}.
025 *
026 * @author Carl Harris
027 */
028public abstract class ServerSocketListener<T extends Client> implements ServerListener<T> {
029
030    private final ServerSocket serverSocket;
031
032    /**
033     * Constructs a new listener.
034     * @param serverSocket server socket delegate
035     */
036    public ServerSocketListener(ServerSocket serverSocket) {
037        this.serverSocket = serverSocket;
038    }
039
040    /**
041     * {@inheritDoc}
042     */
043    public T acceptClient() throws IOException {
044        Socket socket = serverSocket.accept();
045        return createClient(socketAddressToString(socket.getRemoteSocketAddress()), socket);
046    }
047
048    /**
049     * Creates the client object for a new socket connection
050     * @param id identifier string for the client
051     * @param socket client's socket connection
052     * @return client object
053     * @throws IOException
054     */
055    protected abstract T createClient(String id, Socket socket) throws IOException;
056
057    /**
058     * {@inheritDoc}
059     */
060    public void close() {
061        CloseUtil.closeQuietly(serverSocket);
062    }
063
064    /**
065     * {@inheritDoc}
066     */
067    @Override
068    public String toString() {
069        return socketAddressToString(serverSocket.getLocalSocketAddress());
070    }
071
072    /**
073     * Converts a socket address to a reasonable display string.
074     * @param address the subject socket address
075     * @return display string
076     */
077    private String socketAddressToString(SocketAddress address) {
078        String addr = address.toString();
079        int i = addr.indexOf("/");
080        if (i >= 0) {
081            addr = addr.substring(i + 1);
082        }
083        return addr;
084    }
085
086}