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(int port, int backlog, InetAddress bindAddr) throws IOException 

Source Link

Document

Create a server with the specified port, listen backlog, and local IP address to bind to.

Usage

From source file:org.apache.flink.runtime.taskexecutor.TaskManagerRunnerStartupTest.java

/**
 * Tests that the TaskManagerRunner startup fails if the network stack cannot be initialized.
 *//*from  w ww  .j a  v a2  s .  co m*/
@Test
public void testStartupWhenNetworkStackFailsToInitialize() throws Exception {
    final ServerSocket blocker = new ServerSocket(0, 50, InetAddress.getByName(LOCAL_HOST));

    try {
        final Configuration cfg = new Configuration();
        cfg.setInteger(NetworkEnvironmentOptions.DATA_PORT, blocker.getLocalPort());

        startTaskManager(cfg, rpcService, highAvailabilityServices);

        fail("Should throw IOException when the network stack cannot be initialized.");
    } catch (IOException e) {
        // ignored
    } finally {
        IOUtils.closeQuietly(blocker);
    }
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContextCollection.java

public ServerSocket createServerSocket(int port, int backlog, InetAddress bindAddress) throws IOException {
    return new ServerSocket(port, 50, bindAddress);
}

From source file:me.neatmonster.spacertk.PanelListener.java

@Override
public void run() {
    if (mode == 0) {

        try {//from   w  ww. j a v  a 2  s  .c o m
            serverSocket = new ServerSocket(SpaceRTK.getInstance().rPort, SO_BACKLOG,
                    SpaceRTK.getInstance().bindAddress);
            serverSocket.setSoTimeout(SO_TIMEOUT);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        while (!serverSocket.isClosed()) {
            try {
                final Socket clientSocket = serverSocket.accept();
                new PanelListener(clientSocket);
            } catch (SocketTimeoutException e) {
                // Do nothing.
            } catch (Exception e) {
                if (!e.getMessage().contains("socket closed"))
                    e.printStackTrace();
            }
        }
    } else {
        try {
            final BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String string = input.readLine();
            if (string == null) {
                return;
            }
            string = URLDecoder.decode(string, "UTF-8");
            string = string.substring(5, string.length() - 9);
            final PrintWriter output = new PrintWriter(socket.getOutputStream());
            if (string.startsWith("call") && string.contains("?method=") && string.contains("&args=")) {
                final String method = string.substring(12, string.indexOf("&args="));
                if (string.contains("&key=" + Utilities.crypt(method + SpaceRTK.getInstance().salt))) {
                    if (string.startsWith("call?method=DOWNLOAD_WORLD")) {
                        final boolean wasRunning = RemoteToolkit.isRunning();
                        if (wasRunning)
                            RemoteToolkit.hold();
                        final File file = new File(string.split("\"")[1] + ".zip");
                        ZIP.zip(file, new File(string.split("\"")[1]));
                        if (file.exists()) {
                            final FileInputStream fileInputStream = new FileInputStream(file);
                            final byte[] fileData = new byte[65536];
                            int length;
                            output.println("HTTP/1.1 200 OK");
                            output.println("Content-Type: application/force-download; name=" + file.getName());
                            output.println("Content-Transfer-Encoding: binary");
                            output.println("Content-Length:" + file.length());
                            output.println("Content-Disposition: attachment; filename=" + file.getName());
                            output.println("Expires: 0");
                            output.println("Cache-Control: no-cache, must-revalidate");
                            output.println("Pragma: no-cache");
                            while ((length = fileInputStream.read(fileData)) > 0)
                                output.print(new String(fileData, 0, length));
                            fileInputStream.close();
                        } else
                            output.println(Utilities.addHeader(null));
                        if (wasRunning)
                            RemoteToolkit.unhold();
                    } else {
                        final Object result = interpret(string);
                        if (result != null)
                            try {
                                output.println(Utilities.addHeader(JSONValue.toJSONString(result)));
                            } catch (OutOfMemoryError e) {
                                System.gc();
                                output.println(Utilities.addHeader(null));
                            }
                        else
                            output.println(Utilities.addHeader(null));
                    }
                } else
                    output.println(Utilities.addHeader("Incorrect Salt supplied. Access denied!"));
            } else if (string.startsWith("multiple") && string.contains("?method=")
                    && string.contains("&args=")) {
                final String method = string.substring(16, string.indexOf("&args="));
                if (string.contains("&key=" + Utilities.crypt(method + SpaceRTK.getInstance().salt))) {
                    final Object result = interpretm(string);
                    if (result != null)
                        try {
                            output.println(Utilities.addHeader(JSONValue.toJSONString(result)));
                        } catch (OutOfMemoryError e) {
                            System.gc();
                            output.println(Utilities.addHeader(null));
                        }
                    else
                        output.println(Utilities.addHeader(null));
                } else
                    output.println(Utilities.addHeader("Incorrect Salt supplied. Access denied!"));
            } else if (string.startsWith("ping"))
                output.println(Utilities.addHeader("Pong!"));
            else
                output.println(Utilities.addHeader(null));
            output.flush();
            input.close();
            output.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:me.neatmonster.spacebukkit.PanelListener.java

@Override
public void run() {
    if (mode == 0) {

        try {//from  w w  w . j ava 2 s  .  c  om
            serverSocket = new ServerSocket(SpaceBukkit.getInstance().port, SO_BACKLOG,
                    SpaceBukkit.getInstance().bindAddress);
            serverSocket.setSoTimeout(SO_TIMEOUT);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        while (running && !serverSocket.isClosed()) {
            try {
                final Socket clientSocket = serverSocket.accept();
                new PanelListener(clientSocket);
            } catch (SocketTimeoutException e) {
                // Do nothing.
            } catch (IOException e) {
                if (!e.getMessage().toLowerCase().contains("socket closed"))
                    e.printStackTrace();
            }
        }
    } else {
        try {
            final BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String string = input.readLine();
            if (string == null) {
                return;
            }
            string = URLDecoder.decode(string, "UTF-8");
            string = string.substring(5, string.length() - 9);
            final PrintWriter output = new PrintWriter(socket.getOutputStream());
            if (string.startsWith("call") && string.contains("?method=") && string.contains("&args=")) {
                final String method = string.substring(12, string.indexOf("&args="));
                if (string.contains("&key=" + Utilities.crypt(method + SpaceBukkit.getInstance().salt))) {
                    final Object result = interpret(string);
                    if (result != null)
                        try {
                            output.println(Utilities.addHeader(JSONValue.toJSONString(result)));
                        } catch (OutOfMemoryError e) {
                            System.gc();
                            output.println(Utilities.addHeader(null));
                        }
                    else
                        output.println(Utilities.addHeader(null));
                } else
                    output.println(Utilities.addHeader("Incorrect Salt supplied. Access denied!"));
            } else if (string.startsWith("multiple") && string.contains("?method=")
                    && string.contains("&args=")) {
                final String method = string.substring(16, string.indexOf("&args="));
                if (string.contains("&key=" + Utilities.crypt(method + SpaceBukkit.getInstance().salt))) {
                    final Object result = interpretm(string);
                    if (result != null)
                        try {
                            output.println(Utilities.addHeader(JSONValue.toJSONString(result)));
                        } catch (OutOfMemoryError e) {
                            System.gc();
                            output.println(Utilities.addHeader(null));
                        }
                    else
                        output.println(Utilities.addHeader(null));
                } else
                    output.println(Utilities.addHeader("Incorrect Salt supplied. Access denied!"));
            } else if (string.startsWith("ping"))
                output.println(Utilities.addHeader("Pong!"));
            else
                output.println(Utilities.addHeader(null));
            output.flush();
            input.close();
            output.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesRequestsHandler.java

public void run() {
    try {/*from  ww w.  ja va  2s.c  o m*/
        srv = new ServerSocket(bindAddress.getPort(), 200, bindAddress.getAddress());
    } catch (IOException ex) {
        log.error("Error during server socket creation, thread cannot start", ex);
        return;
    }
    isRunning = true;
    while (isRunning) {
        try {
            Socket skt = srv.accept();
            skt.setSoTimeout(30000);
            HttpWorker worker = new HttpWorker(skt, log, handledDevices, this);
            while (httpWorkers.size() >= MAX_HTTP_WORKERS) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    // ignore
                }
            }
            Thread workerThread = new Thread(worker,
                    "UPNPMBeanDevicesRequestsHandler Http Worker " + httpWorkers.size());
            workerThread.start();
            synchronized (httpWorkers) {
                httpWorkers.add(worker);
            }
        } catch (IOException ex) {
            if (isRunning) {
                log.error("Error during client socket creation", ex);
            }
        }
    }
}

From source file:org.apache.flink.runtime.taskmanager.TaskManagerStartupTest.java

/**
 * Tests that the task manager start-up fails if the network stack cannot be initialized.
 * @throws Exception//from   w w  w .j  ava 2 s.  c  o  m
 */
@Test(expected = IOException.class)
public void testStartupWhenNetworkStackFailsToInitialize() throws Exception {

    ServerSocket blocker = null;

    try {
        blocker = new ServerSocket(0, 50, InetAddress.getByName("localhost"));

        final Configuration cfg = new Configuration();
        cfg.setString(ConfigConstants.TASK_MANAGER_HOSTNAME_KEY, "localhost");
        cfg.setInteger(ConfigConstants.TASK_MANAGER_DATA_PORT_KEY, blocker.getLocalPort());
        cfg.setInteger(ConfigConstants.TASK_MANAGER_MEMORY_SIZE_KEY, 1);

        TaskManager.startTaskManagerComponentsAndActor(cfg, ResourceID.generate(), null, "localhost",
                Option.<String>empty(), Option.<LeaderRetrievalService>empty(), false, TaskManager.class);
    } finally {
        if (blocker != null) {
            try {
                blocker.close();
            } catch (IOException e) {
                // ignore, best effort
            }
        }
    }
}

From source file:com.adito.install.forms.WebServerForm.java

private static boolean isHostAndPortValid(String address, int port) {
    ServerSocket socket = null;//  ww w  .  ja  v a  2 s.  com
    try {
        if (log.isInfoEnabled())
            log.info("Testing listener on " + address + ":" + port);
        socket = new ServerSocket(port, 0, InetAddress.getByName(address));
        return true;
    } catch (IOException e) {
        log.error("Failed to setup server socket.", e);
        return false;
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:net.timewalker.ffmq4.listeners.tcp.io.TcpListener.java

private ServerSocket createServerSocket(int port, int tcpBackLog, InetAddress localAddr, boolean useSSL)
        throws JMSException {
    try {//from   ww  w. j a  va  2 s .co m
        if (useSSL) {
            SSLServerSocket socket = (SSLServerSocket) createSSLContext().getServerSocketFactory()
                    .createServerSocket(port, tcpBackLog, localAddr);
            socket.setNeedClientAuth(false);
            return socket;
        } else
            return new ServerSocket(port, tcpBackLog, localAddr);
    } catch (Exception e) {
        throw new FFMQException("Cannot create server socket", "NETWORK_ERROR", e);
    }
}

From source file:com.alecgorge.minecraft.jsonapi.NanoHTTPD.java

/**
 * Starts a HTTP server to given port./*from w  ww  .jav  a  2 s. co m*/
 * <p>
 * Throws an IOException if the socket is already in use
 */
public NanoHTTPD(int port, boolean ssl, InetAddress bindAddress) throws IOException {
    myTcpPort = port;

    if (ssl) {
        ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
        myServerSocket = ssocketFactory.createServerSocket(port);
    } else {
        if (bindAddress != null) {
            myServerSocket = new ServerSocket(myTcpPort, /* default value */-1, bindAddress);
        } else {
            myServerSocket = new ServerSocket(myTcpPort);
        }
    }
    myThread = new Thread(new Runnable() {
        public void run() {
            try {
                while (true)
                    new HTTPSession(myServerSocket.accept());
            } catch (IOException ioe) {
            }
        }
    });
    myThread.setDaemon(true);
    myThread.start();
}

From source file:at.tugraz.ist.akm.webservice.server.SimpleWebServer.java

public synchronized boolean startServer() {
    if (false == mWakeLock.isHeld()) {
        mWakeLock.acquire();/*  w ww  .  j  av  a  2 s .co  m*/
    }
    if (this.isRunning()) {
        mLog.info("web service is already running at port [" + mServerThread.getPort() + "]");
        return true;
    }

    try {
        if (mServerConfig.isHttpsEnabled) {
            initSSLContext();
            final SSLServerSocketFactory sslServerSocketFactory = mSSLContext.getServerSocketFactory();
            mServerSocket = sslServerSocketFactory.createServerSocket(mServerConfig.port, 0, mSocketAddress);
        } else {
            mServerSocket = new ServerSocket(mServerConfig.port, 0, mSocketAddress);
        }
        statusbarIndicateConnectionUrl();
        mServerSocket.setReuseAddress(true);
        mServerSocket.setSoTimeout(2000);
        mIsServerRunning = true;
        mServerThread = new ServerThread(mServerSocket, mHttpContext, mRegistry);
        mServerThread.setDaemon(true);
        mServerThread.start();
        mLog.info("server started at port [" + mServerConfig.port + "]");

        return true;
    } catch (IOException ioException) {
        mLog.error("cannot bind [" + mServerConfig.protocolName + "] socket to [" + mSocketAddress + ":"
                + mServerConfig.port + "]", ioException);
        return false;
    }

}