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:edu.asu.ser.jsonrpc.lite.server.AbstractServer.java

/**
 * constructor for abstract server type//from   www  .j a  v a  2 s  .co m
 * @param ob : object of class with server methods
 * @param socket: socket number at which server will accept requests
 * @throws IOException: in case of Socket is invalid
 */
protected AbstractServer(Object ob, int socket) throws IOException {
    servSock = new ServerSocket(socket);
    this.ob = ob;
    logger = LogManager.getLogger("serverLog");
}

From source file:com.ngdata.hbaseindexer.mr.HBaseIndexingOptionsTest.java

private static int getFreePort() {
    ServerSocket socket = null;/* w  w  w .j  a v  a2s  .  co  m*/
    try {
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } catch (IOException e) {
        throw new RuntimeException("Error finding a free port", e);
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException("Error closing ServerSocket used to detect a free port.", e);
            }
        }
    }
}

From source file:com.talis.platform.testsupport.StubHttp.java

public static int findFreePort() {
    ServerSocket server;//w  w  w .j  a  va2s .c o m
    try {
        server = new ServerSocket(0);
        int port = server.getLocalPort();
        server.close();
        return port;
    } catch (IOException e) {
        throw new RuntimeException("IOException while trying to find a free port", e);
    }
}

From source file:com.barchart.http.server.TestHttpServer.java

@Before
public void setUp() throws Exception {

    server = new HttpServer();

    basic = new TestRequestHandler("basic", false, 0, 0, false, false);
    async = new TestRequestHandler("async", true, 0, 0, false, false);
    asyncDelayed = new TestRequestHandler("async-delayed", true, 50, 0, false, false);
    clientDisconnect = new TestRequestHandler("", true, 500, 500, false, false);
    error = new TestRequestHandler("error", false, 0, 0, true, false);
    channelError = new TestRequestHandler("channel-error", false, 0, 0, false, true);

    infoHandler = new TestRequestHandler("info", false, 0, 0, false, false);
    serviceHandler = new TestRequestHandler("service", false, 0, 0, false, false);

    final ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();//from  w  w  w .  j  a  v a 2 s  .  c o  m
    s.close();

    final HttpServerConfig config = new HttpServerConfig().requestHandler("/basic", basic)
            .address(new InetSocketAddress("localhost", port)).parentGroup(new NioEventLoopGroup(1))
            .childGroup(new NioEventLoopGroup(1)).requestHandler("/async", async)
            .requestHandler("/async-delayed", asyncDelayed)
            .requestHandler("/client-disconnect", clientDisconnect)
            .requestHandler("/channel-error", channelError).requestHandler("/error", error)
            .requestHandler("/service/info", infoHandler).requestHandler("/service", serviceHandler)
            .maxConnections(1);

    server.configure(config).listen().sync();

    client = new DefaultHttpClient(new PoolingClientConnectionManager());

}

From source file:com.connectsdk.service.netcast.NetcastHttpServer.java

public void start() {
    //TODO: this method is too complex and should be refactored
    if (running)//from   ww  w  .  j a  v  a  2 s .c  o m
        return;

    running = true;

    try {
        welcomeSocket = new ServerSocket(this.port);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    while (running) {
        if (welcomeSocket == null || welcomeSocket.isClosed()) {
            stop();
            break;
        }

        Socket connectionSocket = null;
        BufferedReader inFromClient = null;
        DataOutputStream outToClient = null;

        try {
            connectionSocket = welcomeSocket.accept();
        } catch (IOException ex) {
            ex.printStackTrace();
            // this socket may have been closed, so we'll stop
            stop();
            return;
        }

        String str = null;
        int c;
        StringBuilder sb = new StringBuilder();

        try {
            inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

            while ((str = inFromClient.readLine()) != null) {
                if (str.equals("")) {
                    break;
                }
            }

            while ((c = inFromClient.read()) != -1) {
                sb.append((char) c);
                String temp = sb.toString();

                if (temp.endsWith("</envelope>"))
                    break;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        String body = sb.toString();

        Log.d(Util.T, "got message body: " + body);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = dateFormat.format(calendar.getTime());
        String androidOSVersion = android.os.Build.VERSION.RELEASE;

        PrintWriter out = null;

        try {
            outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            out = new PrintWriter(outToClient);
            out.println("HTTP/1.1 200 OK");
            out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1");
            out.println("Cache-Control: no-store, no-cache, must-revalidate");
            out.println("Date: " + date);
            out.println("Connection: Close");
            out.println("Content-Length: 0");
            out.println();
            out.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                inFromClient.close();
                out.close();
                outToClient.close();
                connectionSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        InputStream stream = null;

        try {
            stream = new ByteArrayInputStream(body.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }

        NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser();

        SAXParser saxParser;
        try {
            saxParser = saxParserFactory.newSAXParser();
            saxParser.parse(stream, handler);
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }

        if (body.contains("ChannelChanged")) {
            ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject());

            Log.d(Util.T, "Channel Changed: " + channel.getNumber());

            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked")
                        ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                .get(i);
                        Util.postSuccess(listener, channel);
                    }
                }
            }
        } else if (body.contains("KeyboardVisible")) {
            boolean focused = false;

            TextInputStatusInfo keyboard = new TextInputStatusInfo();
            keyboard.setRawData(handler.getJSONObject());

            try {
                JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget");
                focused = (Boolean) currentWidget.get("focus");
                keyboard.setFocused(focused);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Log.d(Util.T, "KeyboardFocused?: " + focused);

            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked")
                        ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                .get(i);
                        Util.postSuccess(listener, keyboard);
                    }
                }
            }
        } else if (body.contains("TextEdited")) {
            System.out.println("TextEdited");

            String newValue = "";

            try {
                newValue = handler.getJSONObject().getString("value");
            } catch (JSONException ex) {
                ex.printStackTrace();
            }

            Util.postSuccess(textChangedListener, newValue);
        } else if (body.contains("3DMode")) {
            try {
                String enabled = (String) handler.getJSONObject().get("value");
                boolean bEnabled;

                bEnabled = enabled.equalsIgnoreCase("true");

                for (URLServiceSubscription<?> sub : subscriptions) {
                    if (sub.getTarget().equalsIgnoreCase("3DMode")) {
                        for (int i = 0; i < sub.getListeners().size(); i++) {
                            @SuppressWarnings("unchecked")
                            ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                    .get(i);
                            Util.postSuccess(listener, bEnabled);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.l2jfree.gameserver.status.Status.java

License:asdf

public Status() throws IOException {
    super("Status");
    L2Properties telnetSettings = new L2Properties(L2AutoInitialization.TELNET_FILE);

    _statusPort = Integer.parseInt(telnetSettings.getProperty("StatusPort", "12345"));
    _statusPw = telnetSettings.getProperty("StatusPW");
    if (_statusPw == null) {
        _log.warn("Server's Telnet Function Has No Password Defined!");
        _log.warn("A Password Has Been Automaticly Created!");
        _statusPw = generateRandomPassword(10);
        _log.warn("Password Has Been Set To: " + _statusPw);
    }/*from ww  w.  j av a  2  s  .  c om*/
    _log.info("Telnet StatusServer started successfully, listening on Port: " + _statusPort);
    statusServerSocket = new ServerSocket(_statusPort);
    _uptime = System.currentTimeMillis();
}

From source file:org.apache.flink.runtime.clusterframework.BootstrapTools.java

/**
 * Starts an ActorSystem with the given configuration listening at the address/ports.
 * @param configuration The Flink configuration
 * @param listeningAddress The address to listen at.
 * @param portRangeDefinition The port range to choose a port from.
 * @param logger The logger to output log information.
 * @return The ActorSystem which has been started
 * @throws Exception/*from   w ww  .j  av a  2s .  c  o  m*/
 */
public static ActorSystem startActorSystem(Configuration configuration, String listeningAddress,
        String portRangeDefinition, Logger logger) throws Exception {

    // parse port range definition and create port iterator
    Iterator<Integer> portsIterator;
    try {
        portsIterator = NetUtils.getPortRangeFromString(portRangeDefinition);
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid port range definition: " + portRangeDefinition);
    }

    while (portsIterator.hasNext()) {
        // first, we check if the port is available by opening a socket
        // if the actor system fails to start on the port, we try further
        ServerSocket availableSocket = NetUtils.createSocketFromPorts(portsIterator,
                new NetUtils.SocketFactory() {
                    @Override
                    public ServerSocket createSocket(int port) throws IOException {
                        return new ServerSocket(port);
                    }
                });

        int port;
        if (availableSocket == null) {
            throw new BindException("Unable to allocate further port in port range: " + portRangeDefinition);
        } else {
            port = availableSocket.getLocalPort();
            try {
                availableSocket.close();
            } catch (IOException ignored) {
            }
        }

        try {
            return startActorSystem(configuration, listeningAddress, port, logger);
        } catch (Exception e) {
            // we can continue to try if this contains a netty channel exception
            Throwable cause = e.getCause();
            if (!(cause instanceof org.jboss.netty.channel.ChannelException
                    || cause instanceof java.net.BindException)) {
                throw e;
            } // else fall through the loop and try the next port
        }
    }

    // if we come here, we have exhausted the port range
    throw new BindException("Could not start actor system on any port in port range " + portRangeDefinition);
}

From source file:com.barchart.netty.server.http.TestHttpServer.java

@Before
public void setUp() throws Exception {

    basic = new TestRequestHandler("basic", false, 0, 0, false, false);
    async = new TestRequestHandler("async", true, 0, 0, false, false);
    asyncDelayed = new TestRequestHandler("async-delayed", true, 50, 0, false, false);
    clientDisconnect = new TestRequestHandler("", true, 500, 500, false, false);
    error = new TestRequestHandler("error", false, 0, 0, true, false);
    channelError = new TestRequestHandler("channel-error", false, 0, 0, false, true);

    infoHandler = new TestRequestHandler("info", false, 0, 0, false, false);
    serviceHandler = new TestRequestHandler("service", false, 0, 0, false, false);

    chunkedHandler = new ChunkedRequestHandler("chunked");

    final ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();/* w  w  w .  java 2s .  c o m*/
    s.close();
    Thread.sleep(100);

    server = Servers.createHttpServer().requestHandler("/basic", basic).group(new NioEventLoopGroup(1))
            .requestHandler("/async", async).requestHandler("/async-delayed", asyncDelayed)
            .requestHandler("/client-disconnect", clientDisconnect)
            .requestHandler("/channel-error", channelError).requestHandler("/error", error)
            .requestHandler("/service/info", infoHandler).requestHandler("/service", serviceHandler)
            .requestHandler("/chunked", chunkedHandler).maxConnections(1);

    server.listen(port, "localhost").sync();

    connMgr = new PoolingClientConnectionManager();
    client = new DefaultHttpClient(connMgr);

}

From source file:sample.config.RedisConfig.java

private int getPort() throws IOException {
    if (availablePort == null) {
        ServerSocket socket = new ServerSocket(0);
        availablePort = socket.getLocalPort();
        socket.close();/*  www . j ava2s  .  co m*/
    }
    return availablePort;
}

From source file:com.yahoo.gondola.cli.GondolaAgent.java

/**
 * Instantiates a new Gondola agent./*from ww  w. ja  v  a 2  s  .  co m*/
 *
 * @param port the port
 * @throws IOException the io exception
 */
public GondolaAgent(int port) throws IOException {
    ServerSocket serversocket = new ServerSocket(port);
    logger.info("Listening on port " + port);
    Socket socket;
    while ((socket = serversocket.accept()) != null) {
        new Handler(socket).start();
    }
}