Example usage for java.net ServerSocket ServerSocket

List of usage examples for java.net ServerSocket ServerSocket

Introduction

In this page you can find the example usage for java.net ServerSocket ServerSocket.

Prototype

public ServerSocket() throws IOException 

Source Link

Document

Creates an unbound server socket.

Usage

From source file:ezbake.thriftrunner.starters.SimpleStarter.java

boolean serverSocketIsFree(int port) {
    ServerSocket socket = null;//w  w  w  . j  ava 2s .  c  om
    try {
        socket = new ServerSocket();
        socket.setReuseAddress(true);
        socket.bind(new InetSocketAddress(port));
        this.portNumber = socket.getLocalPort();
        return true;
    } catch (final IOException e) {
        return false;
    } finally {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (final IOException e) {
            // should never happen
        }
    }
}

From source file:com.lithium.flow.shell.sshj.SshjTunnel.java

@Nonnull
private ServerSocket buildServerSocket(int tries) throws IOException {
    int count = 0;
    while (true) {
        try {/*from  ww w .j  a v a 2s. c  om*/
            return new ServerSocket();
        } catch (BindException e) {
            if (++count == tries) {
                throw e;
            }
        }
    }
}

From source file:org.apache.catalina.cluster.tcp.Jdk13ReplicationListener.java

public void listen() throws Exception {
    doListen = true;//from  w ww .j ava 2 s .  c o m
    // Get the associated ServerSocket to bind it with
    serverSocket = new ServerSocket();
    serverSocket.bind(new InetSocketAddress(bind, port));
    while (doListen) {
        Socket socket = serverSocket.accept();
        ClusterListenThread t = new ClusterListenThread(socket, new Jdk13ObjectReader(socket, callback));
        t.setDaemon(true);
        t.start();
    } //while
    serverSocket.close();
}

From source file:com.redblackit.web.server.HostNetUtils.java

/**
 * Check if port is available/*from w w w.j  av  a  2  s.  c  om*/
 * 
 * @param port
 * @return
 */
private static boolean isPortAvailable(int port) {
    ServerSocket serverSocket;
    try {
        serverSocket = new ServerSocket();
    } catch (IOException ex) {
        throw new IllegalStateException("Unable to create ServerSocket.", ex);
    }

    try {
        InetSocketAddress sa = new InetSocketAddress(port);
        serverSocket.bind(sa);
        return true;
    } catch (IOException ex) {
        return false;
    } finally {
        try {
            serverSocket.close();
        } catch (IOException ex) {
            // ignore
        }
    }
}

From source file:com.stratuscom.harvester.codebase.ClassServer.java

private void establishServerSocket() throws IOException, SocketException {
    server = new ServerSocket();
    server.setReuseAddress(true);/*from   w w  w. j  a va 2  s  . co m*/
    String initialPortStr = properties.getProperty(Strings.INITIAL_PORT);
    if (initialPortStr == null) {
        throw new LocalizedRuntimeException(MessageNames.BUNDLE_NAME, MessageNames.MISSING_PROPERTY_ENTRY,
                new Object[] { Strings.CLASS_SERVER_PROPERTIES, Strings.INITIAL_PORT });
    }
    int initialPort = Integer.parseInt(initialPortStr);
    for (int port = initialPort; port < initialPort + 100; port++)
        try {
            server.bind(new InetSocketAddress(port));
            logger.log(Level.INFO, MessageNames.CLASS_SERVER_ESTABLISHED,
                    new Object[] { server.getLocalSocketAddress(), server.getLocalPort() });
            break;
        } catch (BindException be) {
            logger.log(Level.FINE, MessageNames.PORT_IN_USE, new Integer[] { port });
        }
}

From source file:gov.hhs.fha.nhinc.lift.proxy.client.ClientConnectorManager.java

/**
 * This method will create a tunnel of a type defined by the properties
 * facade and will then bind a local temporary port for a client app to use
 * to communicate through the proxy tunnel.  Returns an address to the
 * local server a client can talk to./*from w ww  . jav  a2 s .  co m*/
 *
 * @param token
 * @param serverProxyAddress
 * @param serverProxyPort
 * @return
 * @throws IOException
 */
public InetSocketAddress startConnector(RequestToken token, InetAddress serverProxyAddress, int serverProxyPort,
        int bufferSize, ConsumerProxyPropertiesFacade props, SocketClientManagerController controller)
        throws IOException {
    /*
     * Attempts to start up a connection with the desired server proxy.
     */

    // Note that both client and server are closed when the thread completes
    log.debug("Creating Client instance to connect to server proxy: " + serverProxyAddress + ":"
            + serverProxyPort);
    Client client = props.getClientInstance(serverProxyAddress, serverProxyPort, token);

    /*
     * Start up a socket server bound to the local proxy hostname and to a
     * port unique to this request.
     */
    InetAddress localProxyAddress = props.getClientProxyAddress();
    log.debug("Local client proxy address set as: " + localProxyAddress);

    InetSocketAddress connectorAddress = new InetSocketAddress(localProxyAddress, 0);
    log.debug("Starting server socket for client to access on port: " + connectorAddress.getPort());

    // Note that both client and server are closed when the thread completes
    ServerSocket server = new ServerSocket();
    server.bind(connectorAddress);
    log.debug("Creating Server bound: " + server.getInetAddress() + ": " + server.getLocalPort());

    ClientConnector connector = new ClientConnector(server, client, bufferSize, controller);
    Thread conn = new Thread(connector);

    log.debug("Starting new Client Connector thread.");
    conn.start();

    return new InetSocketAddress(server.getInetAddress(), server.getLocalPort());
}

From source file:com.summit.jbeacon.beacons.MultiCastResourceBeacon.java

public void startListening() throws MultiCastResourceBeaconException {
    try {//from w w w.j  av a2  s . c om
        if (hostName == null) {
            hostName = InetAddress.getLocalHost().getHostName();
        }
        listeningSocket = new ServerSocket();
        listeningSocket.setReuseAddress(true);
        listeningSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), getListenPort()), 0);

        if (ip == null) {
            ip = listeningSocket.getInetAddress().getHostAddress();
        }

        listenerThread = new MultiCastResourceListener(listeningSocket);
        new Thread(listenerThread).start();
    } catch (IOException ex) {
        throw new MultiCastResourceBeaconException(ex.getMessage(), ex);
    }
}

From source file:de.kapsi.net.daap.bio.DaapServerBIO.java

/**
 * Binds this server to the SocketAddress supplied by DaapConfig
 * /*from  w  w w  . j  av a2 s.  co m*/
 * @throws IOException
 */
public synchronized void bind() throws IOException {
    if (running)
        return;

    SocketAddress bindAddr = config.getInetSocketAddress();
    int backlog = config.getBacklog();

    ssocket = new ServerSocket();
    ssocket.bind(bindAddr, backlog);

    if (LOG.isInfoEnabled()) {
        LOG.info("DaapServerBIO bound to " + bindAddr);
    }
}

From source file:com.yanzhenjie.andserver.CoreThread.java

@Override
public void run() {
    // HTTP Attribute.
    HttpParams httpParams = createHttpParams();

    // ??/*  www .j  a  v  a  2s  .co m*/
    HttpProcessor httpProcessor = createHttpProcessor();

    // Http?
    HttpRequestHandlerResolver handlerRegistry = registerRequestHandler();

    // HTTP?
    HttpService httpService = createHttpService(httpParams, httpProcessor, handlerRegistry);

    try {
        mServerSocket = new ServerSocket();
        mServerSocket.setReuseAddress(true);
        try {
            mServerSocket.bind(new InetSocketAddress(mPort));
        } catch (final IOException ignored) {
            if (mListener != null)
                Executors.getInstance().handler(new Runnable() {
                    @Override
                    public void run() {
                        mListener.onError(ignored);
                    }
                });
            return;
        }

        if (mListener != null)
            Executors.getInstance().handler(new Runnable() {
                @Override
                public void run() {
                    mListener.onStarted();
                }
            });

        isLoop = true;

        while (isLoop) {
            if (!mServerSocket.isClosed()) {
                Socket socket = mServerSocket.accept();
                DefaultHttpServerConnection serverConnection = new DefaultHttpServerConnection();
                serverConnection.bind(socket, httpParams);

                // Dispatch request handler.
                HandleRequestThread requestTask = new HandleRequestThread(this, httpService, serverConnection);
                requestTask.setDaemon(true);
                Executors.getInstance().executorService(requestTask);
            }
        }
    } catch (final Exception ignored) {
        ignored.printStackTrace();
    } finally {
        shutdown();
    }
}

From source file:NanoHTTPD.java

/**
 * Start the server.// w  w w.  j  a va  2 s  .c o  m
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket
            .bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            try {
                                outputStream = finalAccept.getOutputStream();
                                TempFileManager tempFileManager = tempFileManagerFactory.create();
                                HTTPSession session = new HTTPSession(tempFileManager, inputStream,
                                        outputStream, finalAccept.getInetAddress());
                                while (!finalAccept.isClosed()) {
                                    session.execute();
                                }
                            } catch (Exception e) {
                                // When the socket is closed by the client, we throw our own SocketException
                                // to break the  "keep alive" loop above.
                                if (!(e instanceof SocketException
                                        && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                    e.printStackTrace();
                                }
                            } finally {
                                safeClose(outputStream);
                                safeClose(inputStream);
                                safeClose(finalAccept);
                                unRegisterConnection(finalAccept);
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}