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:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java

@Test
public void testSocketSink() throws Exception {
    final ServerSocket server = new ServerSocket(0);
    final int port = server.getLocalPort();

    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

    Thread sinkRunner = new Thread("Test sink runner") {
        @Override/*w  w  w  .  j av a 2s.  c om*/
        public void run() {
            try {
                SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0);
                simpleSink.open(new Configuration());
                simpleSink.invoke(TEST_MESSAGE + '\n');
                simpleSink.close();
            } catch (Throwable t) {
                error.set(t);
            }
        }
    };

    sinkRunner.start();

    Socket sk = server.accept();
    BufferedReader rdr = new BufferedReader(new InputStreamReader(sk.getInputStream()));

    String value = rdr.readLine();

    sinkRunner.join();
    server.close();

    if (error.get() != null) {
        Throwable t = error.get();
        t.printStackTrace();
        fail("Error in spawned thread: " + t.getMessage());
    }

    assertEquals(TEST_MESSAGE, value);
}

From source file:Networking.Client.java

public Client(int port, Writable toWrite) {
    this.port = port;
    this.writer = toWrite;
    try {//from w  w  w  .ja v a2 s .co m
        server = new ServerSocket(port);
    } catch (IOException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.barchart.netty.rest.client.TestRestClientBase.java

@BeforeClass
public static void init() throws Exception {

    final ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();/*  w ww .  j  a va2  s . c o m*/
    s.close();

    handler = new TestRequestHandler();

    server = new HttpServer().requestHandler("/test", handler);

    server.listen(port).sync();

    client = new RestClientBase("http://localhost:" + port) {
    };

}

From source file:com.polivoto.threading.IncommingRequestHandler.java

@Override
public void run() {
    try {//ww w.  j  av  a 2s. com
        server = new ServerSocket(5010);
        while (true) {
            Socket socket = server.accept();
            new AccionRequerida(socket).start();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.devoteam.srit.xmlloader.http.bio.BIOSocketServerListener.java

/** Creates a new instance of SocketServerHttpListener */
public BIOSocketServerListener(int port, boolean secure) throws ExecutionException {
    super(secure);

    if (secure) {
        StatPool.beginStatisticProtocol(StatPool.LISTENPOINT_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TLS,
                StackFactory.PROTOCOL_HTTP);
    } else {/*from w ww .j a v  a  2s. c  o m*/
        StatPool.beginStatisticProtocol(StatPool.LISTENPOINT_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TCP,
                StackFactory.PROTOCOL_HTTP);
    }
    this.startTimestamp = System.currentTimeMillis();

    try {
        if (secure)
            serverSocket = StackHttp.context.getServerSocketFactory().createServerSocket(port);
        else
            serverSocket = new ServerSocket(port);

        ThreadPool.reserve().start(this);
    } catch (Exception e) {
        throw new ExecutionException("Can't instantiate the HTTP SocketServerListener secure=" + secure, e);
    }
}

From source file:com.l2jfree.status.StatusServer.java

License:asdf

protected StatusServer() throws IOException {
    _socket = new ServerSocket(
            Integer.parseInt(new L2Properties(L2AutoInitialization.TELNET_FILE).getProperty("StatusPort")));

    addFilter(new FloodFilter());
    addFilter(new HostFilter());

    setPriority(Thread.MAX_PRIORITY);
    setDaemon(true);/*  w  w w.  j a v  a2 s  .  com*/
    start();

    _log.info("Telnet: Listening on port: " + getServerSocket().getLocalPort());
}

From source file:au.com.jwatmuff.eventmanager.Main.java

/**
 * Binds to a TCP port to ensure we are the only instance of Event Manager
 * running on the computer. Returns false if the TCP port is already bound
 * and the force parameter is set to false.
 *///from  ww  w  .  ja va 2  s . co  m
private static boolean obtainRunLock(boolean force) {
    if (force)
        return true;
    try {
        final ServerSocket lockSocket = new ServerSocket(LOCK_PORT);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    lockSocket.close();
                } catch (IOException e) {
                    log.warn("Failed to close lock socket", e);
                }
            }
        });
    } catch (IOException e) {
        log.info("Run lock is present");
        return false;
    }

    return true;
}

From source file:com.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxy.java

public void run() {
    ServerSocket serverSocket = null;
    try {/*from   w  w  w .j  a v a2s.c om*/
        serverSocket = new ServerSocket(proxyPort);
        serverSocket.setSoTimeout(timeout);
        // logger.info("Proxy started at " + proxyPort);
        while (!isStopped) {
            try {
                Socket sock = serverSocket.accept();
                HttpProxyWorker worker = new HttpProxyWorker(this, sock);
                Thread t = new Thread(worker);
                t.start();
            } catch (IOException e) {
                ConvertigoPlugin.logException(e, "Unexpected exception");
            }
        }
    } catch (IOException e) {
        ConvertigoPlugin.logException(e, "Unexpected exception");
    }
}

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

public void start() {
    if (running)/*ww w  . ja v a2 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("Connect SDK", "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.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("Connect SDK", "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("Connect SDK", "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;

                if (enabled.equalsIgnoreCase("true"))
                    bEnabled = true;
                else
                    bEnabled = false;

                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:org.apache.servicecomb.it.ITBootListener.java

protected int getRandomPort() {
    try (ServerSocket serverSocket = new ServerSocket(0)) {
        return serverSocket.getLocalPort();
    } catch (IOException e) {
        throw new IllegalStateException("Failed to get random port.", e);
    }/*from w ww.ja v a 2s .com*/
}