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) throws IOException 

Source Link

Document

Creates a server socket, bound to the specified port.

Usage

From source file:com.ksc.http.server.MockServer.java

public void startServer() {
    try {/*  w w  w .  j a  v a2  s.  c  o  m*/
        serverSocket = new ServerSocket(0); // auto-assign a port at localhost
        System.out.println("Listening on port " + serverSocket.getLocalPort());
    } catch (IOException e) {
        throw new RuntimeException("Unable to start the server socker.", e);
    }

    listenerThread = new MockServerListenerThread(serverSocket, serverBehaviorStrategy);
    listenerThread.setDaemon(true);
    listenerThread.start();
}

From source file:org.accada.reader.hal.impl.sim.multi.SimulatorServerController.java

public SimulatorServerController() throws SimulatorServerException {

    // load properties from properties file
    props = new Properties();
    try {/*from w w  w .j  a v  a2 s .  c o  m*/
        props.load(this.getClass().getResourceAsStream(PROPERTIES_FILE_LOCATION));
    } catch (IOException e) {
        throw new SimulatorServerException("Could not load property file.");
    }

    // get properties
    simType = props.getProperty("simType");
    port = Integer.parseInt(props.getProperty("port"));

    // try to open server socket
    try {
        serverSocket = new ServerSocket(port);
    } catch (IOException e) {
        throw new SimulatorServerException("Could not open the server socket.");
    }

    // start register socket
    registerSocket = new RegisterSocket();
    registerSocket.start();

    // try to initialize the MutliSimulatorEngine (GraphicSimulatorServer of BatchSimulatorServer)
    LOG.info("SimulatorServerEngine: " + simType);
    try {
        Class simClass = Class.forName(simType);
        SimulatorServerEngine simulator = (SimulatorServerEngine) simClass.getConstructor(new Class[0])
                .newInstance(new Object[0]);
        simulator.initialize(this);
    } catch (ClassNotFoundException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (IllegalArgumentException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (SecurityException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (InstantiationException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (IllegalAccessException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (InvocationTargetException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (NoSuchMethodException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (SimulatorServerException e) {
        throw new SimulatorServerException(e.getMessage());
    }
}

From source file:SimpleHttpServerDataProvider.java

public SimpleHttpServer(SimpleHttpServerDataProvider dataProvider, int port) {

    class SocketProcessor implements Runnable {
        private Socket s;
        private InputStream is;
        private OutputStream os;
        private SimpleHttpServerDataProvider dataProvider;

        private SocketProcessor(Socket s, SimpleHttpServerDataProvider prov) throws Throwable {
            this.dataProvider = prov;
            this.s = s;
            this.is = s.getInputStream();
            this.os = s.getOutputStream();
        }//from  w  w w.j  av a  2s  . com

        public void run() {
            try {
                readInputHeaders();
                writeResponse("");
            } catch (Throwable t) {
                /*do nothing*/
            } finally {
                try {
                    s.close();
                } catch (Throwable t) {
                    /*do nothing*/
                }
            }

        }

        private void writeResponse(String s) throws Throwable {
            String response = "HTTP/1.1 200 OK\r\n" + "Server: DJudge.http\r\n" + "Content-Type: text/html\r\n"
                    + "Content-Length: " + s.length() + "\r\n" + "Connection: close\r\n\r\n";
            String result = response + dataProvider.getHtmlPage("");
            os.write(result.getBytes());
            os.flush();
        }

        private void readInputHeaders() throws Throwable {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while (true) {
                String s = br.readLine();
                if (s == null || s.trim().length() == 0) {
                    break;
                }

            }
        }
    }

    this.dataProvider = dataProvider;
    try {
        ServerSocket ss = new ServerSocket(port);

        while (true) {
            Socket s = ss.accept();

            new Thread(new SocketProcessor(s, dataProvider)).start();
        }
    } catch (Exception e) {

    } catch (Throwable e) {

    }
}

From source file:AvailablePortFinder.java

/**
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 *//*from   w w  w  .j  a  v  a2s.c o  m*/
public static boolean available(int port) {
    if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    } finally {
        if (ds != null) {
            ds.close();
        }

        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }

    return false;
}

From source file:io.specto.hoverfly.junit.HoverflyRuleUtils.java

static int findUnusedPort() {
    try (final ServerSocket serverSocket = new ServerSocket(0)) {
        return serverSocket.getLocalPort();
    } catch (IOException e) {
        throw new RuntimeException("Cannot find available port", e);
    }//from   w  w w. j  av  a  2s .co  m
}

From source file:edu.umd.cs.marmoset.utilities.UptimeDaemon.java

public UptimeDaemon(File outputDir, int port) throws IOException {
    this.port = port;
    this.outputDir = outputDir;
    this.serverSocket = new ServerSocket(this.port);
    this.hostname = InetAddress.getLocalHost().getHostAddress();
}

From source file:com.yahoo.druid.hadoop.OverlordTestServer.java

private int findFreePort(int startPort) {
    int port = startPort;
    while (true) {
        port++;/*  w  w w  . j  a v  a  2 s.  c  om*/
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(port);
            return port;
        } catch (BindException be) {
            //port in use
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ss != null) {
                while (!ss.isClosed()) {
                    try {
                        ss.close();
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        }
    }
}

From source file:org.accada.hal.impl.sim.multi.SimulatorServerController.java

public SimulatorServerController(String propFile, String defaultPropFile) throws SimulatorServerException {
    // load properties
    try {/*from  www  .j a  v a 2  s . c  o m*/
        URL fileurl = ResourceLocator.getURL(propFile, defaultPropFile, this.getClass());
        propsConfig = new XMLConfiguration(fileurl);
    } catch (ConfigurationException ce) {
        throw new SimulatorServerException("Could not load property file.");
    }

    // get properties
    simType = propsConfig.getString("simType");
    String simTypePropFile = propsConfig.getString("simTypePropFile");
    port = propsConfig.getInt("port");

    // try to open server socket
    try {
        serverSocket = new ServerSocket(port);
    } catch (IOException e) {
        throw new SimulatorServerException("Could not open the server socket.");
    }

    // start register socket
    registerSocket = new RegisterSocket();
    registerSocket.start();

    // try to initialize the MutliSimulatorEngine (GraphicSimulatorServer or BatchSimulatorServer)
    LOG.info("SimulatorServerEngine: " + simType);
    try {
        Class simClass = Class.forName(simType);
        SimulatorServerEngine simulator = (SimulatorServerEngine) simClass.getConstructor(new Class[0])
                .newInstance(new Object[0]);
        simulator.initialize(this, simTypePropFile, simTypeDefaultPropFile);
    } catch (ClassNotFoundException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (IllegalArgumentException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (SecurityException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (InstantiationException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (IllegalAccessException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (InvocationTargetException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (NoSuchMethodException e) {
        throw new SimulatorServerException(e.getMessage());
    } catch (SimulatorServerException e) {
        throw new SimulatorServerException(e.getMessage());
    }
}

From source file:com.replaymod.replaystudio.launcher.DaemonLauncher.java

public void launch(CommandLine cmd) throws Exception {
    int threads = Integer.parseInt(cmd.getOptionValue('d', "" + Runtime.getRuntime().availableProcessors()));
    worker = Executors.newFixedThreadPool(threads);

    System.setOut(new PrintStream(systemOut = new ThreadLocalOutputStream(System.out)));
    ServerSocket serverSocket = new ServerSocket(PORT);
    System.out.println("Daemon started on port " + PORT + " with " + threads + " worker threads.");
    while (!Thread.interrupted()) {
        Socket socket = serverSocket.accept();
        try {//from w ww  .j ava  2  s .c  om
            Client client = new Client(socket);
            new Thread(client).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.wso2.carbon.automation.extensions.servers.httpserver.SimpleHttpServer.java

public void start() throws IOException {
    serverSocket = new ServerSocket(port);
    params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
            getParameter(CoreConnectionPNames.SO_TIMEOUT, 60000))
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
                    getParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024))
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,
                    getParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, 0) == 1)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,
                    getParameter(CoreConnectionPNames.TCP_NODELAY, 1) == 1)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "WSO2ESB-Test-Server");
    // Configure HTTP protocol processor
    BasicHttpProcessor httpProcessor = new BasicHttpProcessor();
    httpProcessor.addInterceptor(new ResponseDate());
    httpProcessor.addInterceptor(new ResponseServer());
    httpProcessor.addInterceptor(new ResponseContent());
    httpProcessor.addInterceptor(new ResponseConnControl());
    HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
    registry.register("*", requestHandler);
    // Set up the HTTP service
    httpService = new HttpService(httpProcessor, new DefaultConnectionReuseStrategy(),
            new DefaultHttpResponseFactory(), registry, params);
    listener = Executors.newSingleThreadExecutor();
    workerPool = Executors.newFixedThreadPool(getParameter("ThreadCount", 2));
    shutdown = false;// w  ww.j av a  2s  .co m
    listener.submit(new HttpListener());
}