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:eu.fusepool.p3.proxy.ProxyTest.java

public static int findFreePort() {
    int port = 0;
    try (ServerSocket server = new ServerSocket(0);) {
        port = server.getLocalPort();//  ww w .ja  v  a  2 s . c  om
    } catch (Exception e) {
        throw new RuntimeException("unable to find a free port");
    }
    return port;
}

From source file:acoli.controller.Controller.java

/**
 * http://stackoverflow.com/questions/434718/sockets-discover-port-availability-using-java
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 *///w ww.j ava 2s  .c  om
public static boolean portAvailable(int port) {
    int MIN_PORT_NUMBER = 1000;
    int MAX_PORT_NUMBER = 9999;
    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:com.ejisto.util.IOUtils.java

private static boolean isPortAvailable(int port) {
    try (DatagramSocket udp = new DatagramSocket(port); ServerSocket tcp = new ServerSocket(port)) {
        tcp.setReuseAddress(true);//from  w w  w  .j  a  va 2 s .c  o  m
        udp.setReuseAddress(true);
        return true;
    } catch (IOException ex) {
        return false;
    }
}

From source file:com.zju.ccnt.or.OpenReplicator.java

@Override
public void run() {
    initPacketHandlers();//ww w .  jav a 2 s.c om
    try {
        ss = new ServerSocket(clientport);
    } catch (IOException e1) {
        e1.printStackTrace();
        return;
    }
    this.running.set(true);
    while (this.running.get()) {
        long writeTime = 0;
        long n1, n2;
        try {
            clientTransport = new TransportImpl(ss.accept(), readBufferSize, writeBufferSize, writeSize,
                    writeSocketInterval);
            mysqlTransport = new TransportImpl(new Socket(host, port), readBufferSize, 32 * 1024, 100,
                    writeSocketInterval);
            // connect
            connect(clientTransport, mysqlTransport);
            // login
            login(clientTransport, mysqlTransport);
            // dump
            utilDumpBin(clientTransport, mysqlTransport);

            this.binlogParser = getDefaultBinlogParser(mysqlTransport);

            int count = 0;
            while (this.running.get()) {
                List<AbstractPacket> list = getEventPackets(mysqlTransport, clientTransport);
                count += list.size();
                AbstractBinlogEventV4 event = null;
                event = this.binlogParser.doParse(list);
                if (event != null && this.binlogEventListener != null) {
                    boolean re = this.binlogEventListener.accept(event);
                    if (!re) {
                        for (AbstractPacket p : list) {
                            // System.out.println(p.getSequence());
                            byte[] newb = new byte[5];
                            newb[0] = 1;
                            newb[3] = (byte) p.getSequence();
                            newb[4] = 0;
                            p.setLength(1);
                            p.setBytes(newb);
                        }
                    }
                }
                n1 = System.currentTimeMillis();
                for (AbstractPacket p : list) {
                    clientTransport.writePacket(p);
                }
                n2 = System.currentTimeMillis();
                writeTime += (n2 - n1);

                if (count % 50000 == 0) {
                    // System.err.println("body time:"+TransportOutputStreamImpl.bodytime);
                    System.err.println("write time:" + writeTime);
                    // System.err.println("wait time:"+ByteLinkedBlockingDeque.waitTime);
                    // System.err.println("write time:"+ByteLinkedBlockingDeque.writeTime);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (clientTransport != null) {
                try {
                    clientTransport.disconnect();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (mysqlTransport != null) {
                try {
                    mysqlTransport.disconnect();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:com.altiscale.TcpProxy.HostPort.java

public void init(ProxyConfiguration conf) {
    config = conf;//from w  ww. j a  v a  2  s.co m

    // Launch ServerStats thread.
    new Thread(new ServerStatus(this, config.statusPort)).start();

    // Initialize servers and optional ssh tunnels via jumphost.
    for (HostPort serverHostPort : config.serverHostPortList) {
        Server server = null;
        if (null == config.jumphost) {
            server = new Server(serverHostPort);
        } else {
            server = new Server(serverHostPort, config.jumphost);
            server.startJumphostThread();
        }
        assert null != server;
        serverList.add(server);
    }

    // Open our listening port.
    tcpProxyPort = config.listeningPort;
    try {
        tcpProxyService = new ServerSocket(tcpProxyPort);
        LOG.info("Listening for incoming clients on port " + tcpProxyPort);
    } catch (IOException ioe) {
        LOG.error("IO exception while establishing proxy service on port " + tcpProxyPort);
        System.exit(1);
    }

    // Set load balancer.
    if (config.loadBalancerString.equals("LeastUsed")) {
        loadBalancer = new LeastUsed(getServerList());
    } else if (config.loadBalancerString.equals("UniformRandom")) {
        loadBalancer = new UniformRandom(getServerList());
    } else {
        loadBalancer = new RoundRobin(getServerList());
    }
    setLoadBalancer(loadBalancer);
}

From source file:com.example.networkPacketFormats.ServeFunction.java

public TCPServer(Connection con) {
    System.out.println("saf");
    try {// w w w. j  ava  2 s.  c o m
        socket = new ServerSocket(6711);
        socket.setReuseAddress(true);
    } catch (IOException ex) {
        Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
    }
    this.con = con;
}

From source file:net.sbbi.upnp.ServicesEventing.java

public void run() {
    // only the deamon thread is allowed to call such method
    if (!Thread.currentThread().getName().equals("ServicesEventing daemon"))
        return;/*w w  w .  j a v a2 s . c o m*/
    try {
        server = new ServerSocket(daemonPort);
    } catch (IOException ex) {
        log.error("Error during daemon server socket on port " + daemonPort + " creation", ex);
        return;
    }
    while (inService) {
        try {
            Socket skt = server.accept();
            new Thread(new RequestProcessor(skt)).start();
        } catch (IOException ioEx) {
            if (inService) {
                log.error("IO Exception during UPNP messages listening thread", ioEx);
            }
        }
    }
}

From source file:com.lfv.lanzius.server.LanziusServer.java

private void groupRemoteControlListener(final int port) {
    new Thread("RemoteControlThread") {
        public void run() {
            try {
                ServerSocket serverSocket = new ServerSocket(port);
                Socket socket = null;
                boolean listening = true;
                String inputLine;
                while (listening) {
                    socket = serverSocket.accept();
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    inputLine = in.readLine();
                    log.debug("Remote control thread received: " + inputLine);
                    try {
                        String arglist[];
                        arglist = inputLine.split(" ");
                        String command = arglist[0];

                        if (command.equals("play")) {
                            String newtime;
                            String comment;

                            if (arglist.length >= 2)
                                newtime = arglist[1];
                            else
                                newtime = null;
                            menuChoiceGroupStart(1, false, newtime);
                            if (arglist.length >= 3)
                                comment = arglist[2];
                            else
                                comment = null;

                            if (comment != null) {
                                ServerLogger logger = loggerMap.get(1);
                                if (logger != null) {
                                    logger.print(comment);
                                }/*  w  w w  . j  a  va 2 s.  c  om*/
                            }
                        } else if (command.equals("stop")) {
                            menuChoiceGroupStop(1, false);
                        } else if (command.equals("pause")) {
                            String comment;
                            if (arglist.length >= 2)
                                comment = arglist[1];
                            else
                                comment = null;
                            if (comment != null) {
                                ServerLogger logger = loggerMap.get(1);
                                if (logger != null) {
                                    logger.print(comment);
                                }
                            }
                            menuChoiceGroupPause(1);
                        } else if (inputLine.startsWith("logpath")) {
                            String newlogPath;
                            newlogPath = inputLine.substring(inputLine.indexOf(' ') + 1);
                            ServerLogger logger = loggerMap.get(1);
                            if (logger != null) {
                                log.debug("ServerLogger.logpath=" + logger.getLogPath() + " new path="
                                        + newlogPath);
                                if (newlogPath != logger.getLogPath()) {
                                    log.debug("ServerLogger.logpath changed!!!!");

                                    loggerMap.remove(1);
                                    logger.print("GROUP STOP id[1]");
                                    logger.close();
                                    ServerLogger newlogger = new ServerLogger(1, newlogPath);
                                    loggerMap.put(1, newlogger);
                                    newlogger.print("GROUP START id[1]");
                                }
                            } else {
                                log.debug("No active logger for group 1");
                            }

                            if ((logPath != null) && (!(newlogPath.equals(logPath)))) {
                                log.debug("logPath changed, stopping Groups");
                            }
                            logPath = newlogPath;
                            log.debug("logPath set to " + logPath);
                        }
                    } catch (Exception e) {
                        log.debug("Remote control action failed");
                    }
                    socket.close();
                }
                serverSocket.close();
            } catch (IOException e) {
                log.error("Failed to start Remote Control listener thread!");
                log.error(e.getMessage());
            }
        }
    }.start();
    log.info("Group remote control listening on port " + port + ".");
}

From source file:hudson.plugins.selenium.PluginImpl.java

public Object readResolve() {
    // Update from plugin 2.0 to 2.1 where browsers were introduced
    if (rcFirefoxProfileTemplate != null || rcBrowserSessionReuse != null || rcTrustAllSSLCerts != null
            || rcBrowserSideLog != null) {
        String rcFirefoxProfileTemplate = getDefaultForNull(this.rcFirefoxProfileTemplate, "");
        Boolean rcBrowserSessionReuse = getDefaultForNull(this.rcBrowserSessionReuse, Boolean.FALSE);
        Boolean rcTrustAllSSLCerts = getDefaultForNull(this.rcTrustAllSSLCerts, Boolean.FALSE);
        Boolean rcBrowserSideLog = getDefaultForNull(this.rcBrowserSideLog, Boolean.FALSE);

        List<SeleniumBrowser> browsers = new ArrayList<SeleniumBrowser>();
        browsers.add(new IEBrowser(5, "", ""));
        browsers.add(new FirefoxBrowser(5, "", ""));
        browsers.add(new ChromeBrowser(5, "", ""));

        int port = 4445;
        try {//from   w  w  w  .  j a v  a  2s.c o m
            ServerSocket ss = new ServerSocket(0);
            port = ss.getLocalPort();
            ss.close();
        } catch (IOException e) {
        }

        SeleniumNodeConfiguration c = new CustomRCConfiguration(port, rcBrowserSideLog, rcDebug,
                rcTrustAllSSLCerts, rcBrowserSessionReuse, -1, rcFirefoxProfileTemplate, browsers, null);

        synchronized (configurations) {
            configurations.add(
                    new SeleniumGlobalConfiguration("Selenium v2.0 configuration", new MatchAllMatcher(), c));
        }

    }

    // update to 2.3 where hostname options were introduced
    if (hostnameResolver == null) {
        hostnameResolver = new JenkinsRootHostnameResolver();
    }

    return this;
}

From source file:com.yahoo.pulsar.testclient.LoadSimulationClient.java

public void run() throws Exception {
    final ServerSocket serverSocket = new ServerSocket(port);

    while (true) {
        // Technically, two controllers can be connected simultaneously, but
        // non-sequential handling of commands
        // has not been tested or considered and is not recommended.
        log.info("Listening for controller command...");
        final Socket socket = serverSocket.accept();
        log.info("Connected to {}\n", socket.getInetAddress().getHostName());
        executor.submit(() -> {//from  ww w  .  j  av  a2  s .c  o m
            try {
                handle(socket);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });
    }
}