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.hqme.cm.cache.StreamingServer.java

public void run() {
    if (UntenCacheService.sIsDebugMode) {
        Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
        Thread.currentThread().setName(getClass().getName());
    }//from w w  w .  j av a 2s. com

    isStopping = false;
    serverSocket = null;
    serverPortPrefs = new File(UntenCacheService.sPluginContext.getFilesDir(), tag_PlaybackPortNumber);
    try {
        String text = new BufferedReader(new InputStreamReader(new FileInputStream(serverPortPrefs), "UTF16"),
                1 << 10).readLine();
        serverPortNumber = Integer.valueOf(text.trim());
    } catch (Throwable ignore) {
        serverPortNumber = 0;
    }

    int retries = 2;
    while (retries-- > 0) {
        try {
            serverSocket = new ServerSocket(serverPortNumber);
            if (serverPortNumber == 0) {
                serverPortNumber = serverSocket.getLocalPort();
                try {
                    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(serverPortPrefs),
                            "UTF16");
                    writer.write(serverPortNumber + "\r\n");
                    writer.flush();
                    writer.close();
                } catch (Throwable ignore) {
                }
            }
            clientBox = new ClientBox[MAX_CLIENTS];
            retries = 0;

            UntenCacheService.debugLog(sTag, "run: Streaming Media Server is now active on TCP port # %d",
                    serverPortNumber);
            handleRequests();
        } catch (IOException fault) {
            fault.printStackTrace();
            try {
                serverPortPrefs.delete();
            } catch (Throwable ignore) {
            }
        }
    }
}

From source file:com.chinamobile.bcbsp.pipes.Application.java

/**
 * This method is the constructor.//from   ww w .j  a v a2s .c  o  m
 * @param job
 *        contains BSPJob configuration
 * @param staff
 *        the java compute process
 * @param workerAgent
 *        Protocol that staff child process uses to contact its parent process
 * @param processType
 *        the type of c++ process(for staff or workmanager)
 */
public Application(BSPJob job, Staff staff, WorkerAgentProtocol workerAgent, String processType)
        throws IOException, InterruptedException {
    serverSocket = new ServerSocket(0);
    Map<String, String> env = new HashMap<String, String>();
    env.put("TMPDIR", System.getProperty("java.io.tmpdir"));
    LOG.info("Application: System.getProterty: " + System.getProperty("java.io.tmpdir"));
    env.put("processType", processType);
    env.put("bcbsp.pipes.command.port", Integer.toString(serverSocket.getLocalPort()));
    String bcbspdir = job.getConf().get("bcbsp.log.dir");
    String userdefine = job.getConf().get("userDefine");
    env.put("userDefine", userdefine);
    LOG.info("bcbsp log dir : " + bcbspdir);
    env.put("bcbsp.log.dir", bcbspdir);
    if (processType.equalsIgnoreCase("staff")) {
        env.put("staffID", staff.getStaffID().toString());
        LOG.info("staffID is :" + staff.getStaffID().toString());
    } else {
    }
    List<String> cmd = new ArrayList<String>();
    String executable = staff.getJobExeLocalPath();
    File file = new File(executable);
    if (file.exists()) {
        LOG.info("the jobC is exist");
    } else {
        LOG.info("the jobC is not exist");
    }
    FileUtil.chmod(executable, "a+x");
    cmd.add(executable);

    process = runClient(cmd, env);
    LOG.info("waiting for connect cpp process");
    clientSocket = serverSocket.accept();
    LOG.info("=========run C++ ======");
    this.handler = new TaskHandler(job, staff, workerAgent);
    this.downlink = new BinaryProtocol(clientSocket, handler);
    this.downlink.start();
}

From source file:org.metaeffekt.dcc.agent.DccAgentTest.java

private static int findAvailablePort() throws BindException {

    for (int p = DccAgentEndpoint.DEFAULT_PORT; p < 65535; p++) {

        try {//from  w w  w.ja  va 2 s . c  o  m
            new ServerSocket(p);
            return p;
        } catch (IOException e) {
        }
    }

    throw new BindException("unable to find an available port");

}

From source file:org.urbanstew.soundcloudapi.SoundCloudAPI.java

/**
 * Completes the OAuth 1.0a authorization steps with SoundCloud, assuming the consumer application
 * can use a local port to receive the verification code.
 * /*from ww  w.  ja  va 2  s  .co m*/
 * <p>The function acts as a minimal HTTP server and will listen on the port specified in the
 * <code>url</code> (or the default HTTP port, if no port is specified in the <code>url</code>).  It will provide the
 * specified <code>response</code> when it receives a request for the path specified in the <code>url</code>, and
 * assuming the request includes the verification code, terminate successfully.
 * To all other requests it will respond with a <code>Not Found</code> error, and continue listening.
 * 
 * <p>The following example assumes the consumer application is running on the client's computer / device.
 * Hence, it uses a local URL ("http://localhost:8088/") to receive the verification code callback. The function
 * will listen on specified port 8088 to receive the callback.</p>
 * 
 * <pre>
 * {@code
 *  soundcloudapi.authorizeUsingUrl
*   (
*      "http://localhost:8088/",
*      "Thank you for authorizing",
*      new AuthorizationURLOpener()
*      {
*         public void openAuthorizationURL(String authorizationURL)
*         {
*            System.out.println("Please visit " + authorizationURL);
*         }
*      }
*   );
* }
* </pre>
* 
 * @param url - a callback URL via which the user can provide the verification code.
 * @param response - a response given back to the user when they allow access and get redirected to the callback URL.
 * @param URLOpener - an AuthorizationURLOpener which can open the authorization URL to the user when needed.
*
 * @return true if the process is completed successfully, false if the process was canceled via <code>cancelAuthorizeUsingUrl</code>.  
 *  
 * @throws OAuthCommunicationException 
 * @throws OAuthExpectationFailedException 
 * @throws OAuthNotAuthorizedException 
 * @throws OAuthMessageSignerException 
 * @throws IOException 
        
 * @since 0.9.1
 * @see #cancelAuthorizeUsingUrl()
*/
public boolean authorizeUsingUrl(final String url, final String response,
        final AuthorizationURLOpener URLOpener) throws OAuthMessageSignerException, OAuthNotAuthorizedException,
        OAuthExpectationFailedException, OAuthCommunicationException, IOException {
    mCancelAuthorization = false;
    unauthorize();

    URLOpener.openAuthorizationURL(obtainRequestToken(url));

    URL parsedUrl = new URL(url);
    int port = parsedUrl.getPort();
    if (port == -1)
        port = parsedUrl.getDefaultPort();

    ServerSocket server = null;
    String verificationCode = null;

    try {
        server = new ServerSocket(port);
        server.setSoTimeout(500);

        while (verificationCode == null) {
            Socket socket = null;
            BufferedReader in = null;
            PrintWriter out = null;

            try {
                try {
                    socket = server.accept();
                } catch (java.io.InterruptedIOException e) {
                    if (mCancelAuthorization) {
                        unauthorize();
                        return false;
                    } else
                        continue;
                }
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                String requestedUrl = in.readLine().split("\\s+")[1];

                URL parsedRequestedUrl = new URL("http://localhost" + requestedUrl);
                out = new PrintWriter(socket.getOutputStream(), true);

                if (!parsedRequestedUrl.getPath().equals(parsedUrl.getPath()))
                    out.print("HTTP/1.1 404 Not Found");
                else {
                    out.print("HTTP/1.1 200 OK\n\n" + response);
                    for (String parameter : parsedRequestedUrl.getQuery().split("&")) {
                        String[] keyValue = parameter.split("=");
                        if (keyValue[0].equals("oauth_verifier"))
                            verificationCode = keyValue[1];
                    }
                    if (verificationCode == null)
                        // problem - why didn't we get a verification code?
                        verificationCode = "";
                }
                out.flush();
            } finally {
                closeQuietly(in);
                closeQuietly(out);
                closeQuietly(socket);
            }
        }
    } finally {
        closeQuietly(server);
    }

    if (verificationCode.length() > 0) {
        obtainAccessToken(verificationCode);
        return true;
    } else
        return false;
}

From source file:gobblin.service.FlowConfigTest.java

private static int chooseRandomPort() throws IOException {
    ServerSocket socket = null;//  ww  w.  j a  v  a2s. c o  m
    try {
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:org.glowroot.tests.WebDriverSetup.java

private static int getAvailablePort() throws Exception {
    if (SauceLabs.useSauceLabs()) {
        // glowroot must listen on one of the ports that sauce connect proxies
        // see https://saucelabs.com/docs/connect#localhost
        return 4000;
    } else {//from w ww.  ja  v a 2 s  . c  om
        ServerSocket serverSocket = new ServerSocket(0);
        int port = serverSocket.getLocalPort();
        serverSocket.close();
        return port;
    }
}

From source file:ddf.test.itests.AbstractIntegrationTest.java

private static Integer findPortNumber(Integer portToTry) {
    try {/*from  ww w  .  ja v  a 2s  . c  o  m*/
        placeHolderSocket = new ServerSocket(portToTry);
        placeHolderSocket.setReuseAddress(true);
        return portToTry;
    } catch (Exception e) {
        portToTry += 10;
        LOGGER.debug("Bad port, trying {}", portToTry);
        return findPortNumber(portToTry);
    }
}

From source file:com.clustercontrol.agent.Agent.java

/**
 * ??sendManagerDiscoveryInfo?/*from  w  ww .j  ava 2s  . com*/
 * TCP 24005?????????IP?
 * 
 * @throws Exception
 */
private String receiveManagerDiscoveryInfo() throws Exception {
    int default_port = 24005;
    String portStr = AgentProperties.getProperty("discovery.pingport", Integer.toString(default_port));
    int port = Integer.parseInt(portStr);
    if (port < 1 || port > 65535) {
        port = default_port;
    }
    ServerSocket servSock = null;
    Socket clntSock = null;

    final int BUFSIZE = 256;
    int tmpRecvMsgSize = 0;
    int recvMsgSize = 0;
    byte[] receiveBuf = new byte[BUFSIZE];
    String recvMsg = "";

    try {
        servSock = new ServerSocket(port);

        // ????
        clntSock = servSock.accept();
        m_log.info("connecting to " + clntSock.getRemoteSocketAddress().toString());

        InputStream in = clntSock.getInputStream();
        OutputStream out = clntSock.getOutputStream();

        while ((tmpRecvMsgSize = in.read(receiveBuf)) != -1) {
            out.write(receiveBuf, 0, tmpRecvMsgSize);
            recvMsgSize = tmpRecvMsgSize;
        }

        recvMsg = new String(receiveBuf, 0, recvMsgSize);
        m_log.info("receive message : " + recvMsg);
    } catch (Exception e) {
        m_log.warn("receiveManagerIp " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;
    } finally {
        try {
            if (clntSock != null) {
                clntSock.close();
            }
        } catch (Exception e) {
            m_log.warn("receiveManagerIp: " + e);
        }
        try {
            if (servSock != null) {
                servSock.close();
            }
        } catch (Exception e) {
            m_log.warn("receiveManagerIp: " + e);
        }
    }
    return recvMsg;
}

From source file:fr.cmoatoto.multishare.receiver.NanoHTTPDReceiver.java

/**
 * Starts a HTTP server to given port.//  ww  w. ja  v a  2  s.  co  m
 * <p>
 * Throws an IOException if the socket is already in use
 * 
 * @param
 */
public NanoHTTPDReceiver(int port, File wwwroot, Context context) throws IOException {
    mContext = context;
    myTcpPort = port;
    myRootDir = wwwroot;
    myServerSocket = new ServerSocket(myTcpPort);

    if (myThread != null && myThread.isAlive()) {
        return;
    }

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (true) {
                    new HTTPSession(myServerSocket.accept());
                }
            } catch (IOException ioe) {
            }
        }
    });
    myThread.setPriority(Thread.MIN_PRIORITY);
    myThread.setDaemon(true);
    myThread.start();
}

From source file:com.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java

public static int getFreePort() throws IOException {
    ServerSocket serverSocket = new ServerSocket(0);
    int port = serverSocket.getLocalPort();
    serverSocket.close();/*from   ww w  .  j  a v a 2  s  .c o m*/
    return port;
}