Example usage for java.net ServerSocket setSoTimeout

List of usage examples for java.net ServerSocket setSoTimeout

Introduction

In this page you can find the example usage for java.net ServerSocket setSoTimeout.

Prototype

public synchronized void setSoTimeout(int timeout) throws SocketException 

Source Link

Document

Enable/disable SocketOptions#SO_TIMEOUT SO_TIMEOUT with the specified timeout, in milliseconds.

Usage

From source file:com.apporiented.hermesftp.client.FtpTestClient.java

public String openActiveMode() throws IOException {
    InetAddress addr = NetUtils.getMachineAddress(true);
    String addrStr = addr != null ? addr.getHostAddress() : "127.0.0.1";
    ServerSocket sock = ServerSocketFactory.getDefault().createServerSocket(0, 1, addr);
    sock.setSoTimeout(10000);

    Pattern pattern = Pattern.compile("^([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)$");
    Matcher matcher = pattern.matcher(addrStr);
    if (!matcher.matches()) {
        throw new IOException("Invalid address: " + addrStr);
    }//from ww  w  .j  a  va2s .  co  m
    int p1 = (sock.getLocalPort() >>> FtpConstants.BYTE_LENGTH) & FtpConstants.BYTE_MASK;
    int p2 = sock.getLocalPort() & FtpConstants.BYTE_MASK;

    StringBuffer sb = new StringBuffer();
    sb.append("PORT ");
    sb.append(matcher.group(1));
    sb.append(",");
    sb.append(matcher.group(2));
    sb.append(",");
    sb.append(matcher.group(3));
    sb.append(",");
    sb.append(matcher.group(4));
    sb.append(",");
    sb.append(p1);
    sb.append(",");
    sb.append(p2);

    resetDataSockets();
    activeModeServerSocket = sock;

    sendCommand(sb.toString());

    return getResponse();

}

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.j  a v a  2  s.  com*/
 * <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:org.kde.kdeconnect.Backends.LanBackend.LanLink.java

private void sendPackageInternal(NetworkPackage np, final Device.SendPackageStatusCallback callback,
        PublicKey key) {//from  ww w.j  av  a2  s  .c  o m
    if (session == null) {
        Log.e("KDE/sendPackage", "Not yet connected");
        callback.sendFailure(new NotYetConnectedException());
        return;
    }

    try {

        //Prepare socket for the payload
        final ServerSocket server;
        if (np.hasPayload()) {
            server = openTcpSocketOnFreePort();
            JSONObject payloadTransferInfo = new JSONObject();
            payloadTransferInfo.put("port", server.getLocalPort());
            np.setPayloadTransferInfo(payloadTransferInfo);
        } else {
            server = null;
        }

        //Encrypt if key provided
        if (key != null) {
            np = np.encrypt(key);
        }

        //Send body of the network package
        WriteFuture future = session.write(np.serialize());
        future.awaitUninterruptibly();
        if (!future.isWritten()) {
            //Log.e("KDE/sendPackage", "!future.isWritten()");
            callback.sendFailure(future.getException());
            return;
        }

        //Send payload
        if (server != null) {
            OutputStream socket = null;
            try {
                //Wait a maximum of 10 seconds for the other end to establish a connection with our socket, close it afterwards
                server.setSoTimeout(10 * 1000);
                socket = server.accept().getOutputStream();

                Log.i("KDE/LanLink", "Beginning to send payload");

                byte[] buffer = new byte[4096];
                int bytesRead;
                long progress = 0;
                InputStream stream = np.getPayload();
                while ((bytesRead = stream.read(buffer)) != -1) {
                    //Log.e("ok",""+bytesRead);
                    progress += bytesRead;
                    socket.write(buffer, 0, bytesRead);
                    if (np.getPayloadSize() > 0) {
                        callback.sendProgress((int) (progress / np.getPayloadSize()));
                    }
                }
                socket.flush();
                stream.close();
                Log.i("KDE/LanLink", "Finished sending payload (" + progress + " bytes written)");
            } catch (Exception e) {
                Log.e("KDE/sendPackage", "Exception: " + e);
                callback.sendFailure(e);
                return;
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (Exception e) {
                    }
                }
                try {
                    server.close();
                } catch (Exception e) {
                }
            }
        }

        callback.sendSuccess();

    } catch (Exception e) {
        if (callback != null) {
            callback.sendFailure(e);
        }
    } finally {
        //Make sure we close the payload stream, if any
        InputStream stream = np.getPayload();
        try {
            stream.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.hyperic.hq.bizapp.agent.client.AgentClient.java

private int cmdStart(boolean force) throws AgentInvokeException {
    ServerSocket startupSock;
    ProviderInfo providerInfo;//from w w w  . ja  v  a2  s . c o m
    Properties bootProps;

    // Try to ping the agent one time to see if the agent is already up
    try {
        this.cmdPing(1);
        SYSTEM_OUT.println("Agent already running");
        return -1;
    } catch (AgentConnectionException exc) {
        // Normal operation 
    } catch (AgentRemoteException exc) {
        // Very nearly a normal operation
    }

    bootProps = this.config.getBootProperties();

    try {
        int iSleepTime = getStartupTimeout(bootProps);

        startupSock = new ServerSocket(0);
        startupSock.setSoTimeout(iSleepTime);
    } catch (IOException e) {
        AgentInvokeException ex = new AgentInvokeException(
                "Unable to setup a socket to listen for Agent startup: " + e);
        ex.initCause(e);
        throw ex;
    }

    SYSTEM_OUT.println("- Invoking agent");

    try {
        this.config.setNotifyUpPort(startupSock.getLocalPort());
    } catch (AgentConfigException e) {
        throw new AgentInvokeException("Invalid notify up port: " + startupSock.getLocalPort());
    }

    RunnableAgent runnableAgent = new AgentDaemon.RunnableAgent(this.config);
    agentDaemonThread = new Thread(runnableAgent);
    agentDaemonThread.setName("AgentDaemonMain");
    AgentUpgradeManager.setAgentDaemonThread(agentDaemonThread);
    AgentUpgradeManager.setAgent(runnableAgent);
    agentDaemonThread.setDaemon(true);
    agentDaemonThread.start();
    SYSTEM_OUT.println("- Agent thread running");

    /* Now comes the painful task of figuring out if the agent started correctly. */
    SYSTEM_OUT.println("- Verifying if agent is running...");
    this.verifyAgentRunning(startupSock);
    SYSTEM_OUT.println("- Agent is running");

    // Ask the agent if they have a server setup
    try {
        providerInfo = this.camCommands.getProviderInfo();
    } catch (Exception exc) {
        // This should rarely (never) occur, since we just ensured things
        // were operational.
        throw new AgentInvokeException("Unexpected connection exception: " + "agent is still running");
    }

    SYSTEM_OUT.println("Agent successfully started");

    // Only force a setup if we are not running the agent in Java Service Wrapper mode
    if (providerInfo == null && !WrapperManager.isControlledByNativeWrapper()) {
        SYSTEM_OUT.println();
        return FORCE_SETUP;
    } else {
        redirectOutputs(bootProps); //win32
        return 0;
    }

}

From source file:slash.navigation.mapview.browser.BrowserMapView.java

private ServerSocket createCallbackListenerServerSocket() {
    try {// w  w  w  . jav a2 s. c o  m
        ServerSocket serverSocket = new ServerSocket(0, 0,
                InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }));
        serverSocket.setSoTimeout(1000);
        int port = serverSocket.getLocalPort();
        log.info("Map listens on port " + port + " for callbacks");
        setCallbackListenerPort(port);
        return serverSocket;
    } catch (IOException e) {
        log.severe("Cannot open callback listener socket: " + e);
        return null;
    }
}

From source file:org.apache.hadoop.dfs.DataNode.java

/**
 * This method starts the data node with the specified conf.
 * //from  w  w  w.j  a  va 2  s .c om
 * @param conf - the configuration
 *  if conf's CONFIG_PROPERTY_SIMULATED property is set
 *  then a simulated storage based data node is created.
 * 
 * @param dataDirs - only for a non-simulated storage data node
 * @throws IOException
 */
void startDataNode(Configuration conf, AbstractList<File> dataDirs) throws IOException {
    // use configured nameserver & interface to get local hostname
    if (conf.get("slave.host.name") != null) {
        machineName = conf.get("slave.host.name");
    }
    if (machineName == null) {
        machineName = DNS.getDefaultHost(conf.get("dfs.datanode.dns.interface", "default"),
                conf.get("dfs.datanode.dns.nameserver", "default"));
    }
    InetSocketAddress nameNodeAddr = NameNode.getAddress(conf);

    this.estimateBlockSize = conf.getLong("dfs.block.size", DEFAULT_BLOCK_SIZE);
    this.socketTimeout = conf.getInt("dfs.socket.timeout", FSConstants.READ_TIMEOUT);
    this.socketWriteTimeout = conf.getInt("dfs.datanode.socket.write.timeout", FSConstants.WRITE_TIMEOUT);
    /* Based on results on different platforms, we might need set the default 
     * to false on some of them. */
    this.transferToAllowed = conf.getBoolean("dfs.datanode.transferTo.allowed", true);
    this.writePacketSize = conf.getInt("dfs.write.packet.size", 64 * 1024);
    String address = NetUtils.getServerAddress(conf, "dfs.datanode.bindAddress", "dfs.datanode.port",
            "dfs.datanode.address");
    InetSocketAddress socAddr = NetUtils.createSocketAddr(address);
    int tmpPort = socAddr.getPort();
    storage = new DataStorage();
    // construct registration
    this.dnRegistration = new DatanodeRegistration(machineName + ":" + tmpPort);

    // connect to name node
    this.namenode = (DatanodeProtocol) RPC.waitForProxy(DatanodeProtocol.class, DatanodeProtocol.versionID,
            nameNodeAddr, conf);
    // get version and id info from the name-node
    NamespaceInfo nsInfo = handshake();
    StartupOption startOpt = getStartupOption(conf);
    assert startOpt != null : "Startup option must be set.";

    boolean simulatedFSDataset = conf.getBoolean("dfs.datanode.simulateddatastorage", false);
    if (simulatedFSDataset) {
        setNewStorageID(dnRegistration);
        dnRegistration.storageInfo.layoutVersion = FSConstants.LAYOUT_VERSION;
        dnRegistration.storageInfo.namespaceID = nsInfo.namespaceID;
        // it would have been better to pass storage as a parameter to
        // constructor below - need to augment ReflectionUtils used below.
        conf.set("StorageId", dnRegistration.getStorageID());
        try {
            //Equivalent of following (can't do because Simulated is in test dir)
            //  this.data = new SimulatedFSDataset(conf);
            this.data = (FSDatasetInterface) ReflectionUtils
                    .newInstance(Class.forName("org.apache.hadoop.dfs.SimulatedFSDataset"), conf);
        } catch (ClassNotFoundException e) {
            throw new IOException(StringUtils.stringifyException(e));
        }
    } else { // real storage
        // read storage info, lock data dirs and transition fs state if necessary
        storage.recoverTransitionRead(nsInfo, dataDirs, startOpt);
        // adjust
        this.dnRegistration.setStorageInfo(storage);
        // initialize data node internal structure
        this.data = new FSDataset(storage, conf);
    }

    // find free port
    ServerSocket ss = (socketWriteTimeout > 0) ? ServerSocketChannel.open().socket() : new ServerSocket();
    Server.bind(ss, socAddr, 0);
    ss.setReceiveBufferSize(DEFAULT_DATA_SOCKET_SIZE);
    ss.setSoTimeout(conf.getInt("dfs.dataXceiver.timeoutInMS", 30000)); //30s
    // adjust machine name with the actual port
    tmpPort = ss.getLocalPort();
    selfAddr = new InetSocketAddress(ss.getInetAddress().getHostAddress(), tmpPort);
    this.dnRegistration.setName(machineName + ":" + tmpPort);
    LOG.info("Opened info server at " + tmpPort);

    this.maxXceiverCount = conf.getInt("dfs.datanode.max.xcievers", MAX_XCEIVER_COUNT);
    this.threadGroup = new ThreadGroup("dataXceiveServer");
    this.dataXceiveServer = new Daemon(threadGroup, new DataXceiveServer(ss));
    this.threadGroup.setDaemon(true); // auto destroy when empty

    this.blockReportInterval = conf.getLong("dfs.blockreport.intervalMsec", BLOCKREPORT_INTERVAL);
    this.initialBlockReportDelay = conf.getLong("dfs.blockreport.initialDelay", BLOCKREPORT_INITIAL_DELAY)
            * 1000L;
    if (this.initialBlockReportDelay >= blockReportInterval) {
        this.initialBlockReportDelay = 0;
        LOG.info("dfs.blockreport.initialDelay is greater than " + "dfs.blockreport.intervalMsec."
                + " Setting initial delay to 0 msec:");
    }
    this.heartBeatInterval = conf.getLong("dfs.heartbeat.interval", HEARTBEAT_INTERVAL) * 1000L;
    DataNode.nameNodeAddr = nameNodeAddr;

    this.balancingThrottler = new BlockBalanceThrottler(
            conf.getLong("dfs.balance.bandwidthPerSec", 1024L * 1024));

    //initialize periodic block scanner
    String reason = null;
    if (conf.getInt("dfs.datanode.scan.period.hours", 0) < 0) {
        reason = "verification is turned off by configuration";
    } else if (!(data instanceof FSDataset)) {
        reason = "verifcation is supported only with FSDataset";
    }
    if (reason == null) {
        blockScanner = new DataBlockScanner(this, (FSDataset) data, conf);
    } else {
        LOG.info("Periodic Block Verification is disabled because " + reason + ".");
    }

    //create a servlet to serve full-file content
    String infoAddr = NetUtils.getServerAddress(conf, "dfs.datanode.info.bindAddress", "dfs.datanode.info.port",
            "dfs.datanode.http.address");
    InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
    String infoHost = infoSocAddr.getHostName();
    int tmpInfoPort = infoSocAddr.getPort();
    this.infoServer = new StatusHttpServer("datanode", infoHost, tmpInfoPort, tmpInfoPort == 0);
    InetSocketAddress secInfoSocAddr = NetUtils
            .createSocketAddr(conf.get("dfs.datanode.https.address", infoHost + ":" + 0));
    Configuration sslConf = new Configuration(conf);
    sslConf.addResource(conf.get("https.keystore.info.rsrc", "sslinfo.xml"));
    String keyloc = sslConf.get("https.keystore.location");
    if (null != keyloc) {
        this.infoServer.addSslListener(secInfoSocAddr, keyloc, sslConf.get("https.keystore.password", ""),
                sslConf.get("https.keystore.keypassword", ""));
    }
    this.infoServer.addServlet(null, "/streamFile/*", StreamFile.class);
    this.infoServer.setAttribute("datanode.blockScanner", blockScanner);
    this.infoServer.addServlet(null, "/blockScannerReport", DataBlockScanner.Servlet.class);
    this.infoServer.start();
    // adjust info port
    this.dnRegistration.setInfoPort(this.infoServer.getPort());
    myMetrics = new DataNodeMetrics(conf, dnRegistration.getStorageID());

    //init ipc server
    InetSocketAddress ipcAddr = NetUtils.createSocketAddr(conf.get("dfs.datanode.ipc.address"));
    ipcServer = RPC.getServer(this, ipcAddr.getHostName(), ipcAddr.getPort(),
            conf.getInt("dfs.datanode.handler.count", 3), false, conf);
    ipcServer.start();
    dnRegistration.setIpcPort(ipcServer.getListenerAddress().getPort());

    LOG.info("dnRegistration = " + dnRegistration);
}

From source file:org.eredlab.g4.ccl.net.ftp.FTPClient.java

/**
 * Establishes a data connection with the FTP server, returning
 * a Socket for the connection if successful.  If a restart
 * offset has been set with {@link #setRestartOffset(long)},
 * a REST command is issued to the server with the offset as
 * an argument before establishing the data connection.  Active
 * mode connections also cause a local PORT command to be issued.
 * <p>//from  w w w  .  j a va2  s.  c  o  m
 * @param command  The text representation of the FTP command to send.
 * @param arg The arguments to the FTP command.  If this parameter is
 *             set to null, then the command is sent with no argument.
 * @return A Socket corresponding to the established data connection.
 *         Null is returned if an FTP protocol error is reported at
 *         any point during the establishment and initialization of
 *         the connection.
 * @exception IOException  If an I/O error occurs while either sending a
 *      command to the server or receiving a reply from the server.
 */
protected Socket _openDataConnection_(int command, String arg) throws IOException {
    Socket socket;

    if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE
            && __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE)
        return null;

    if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE) {
        ServerSocket server;
        server = _socketFactory_.createServerSocket(0, 1, getLocalAddress());

        if (!FTPReply.isPositiveCompletion(port(getLocalAddress(), server.getLocalPort()))) {
            server.close();
            return null;
        }

        if ((__restartOffset > 0) && !restart(__restartOffset)) {
            server.close();
            return null;
        }

        if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
            server.close();
            return null;
        }

        // For now, let's just use the data timeout value for waiting for
        // the data connection.  It may be desirable to let this be a
        // separately configurable value.  In any case, we really want
        // to allow preventing the accept from blocking indefinitely.
        if (__dataTimeout >= 0)
            server.setSoTimeout(__dataTimeout);
        socket = server.accept();
        server.close();
    } else { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE

        if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
            return null;

        __parsePassiveModeReply((String) _replyLines.elementAt(0));

        socket = _socketFactory_.createSocket(__passiveHost, __passivePort);
        if ((__restartOffset > 0) && !restart(__restartOffset)) {
            socket.close();
            return null;
        }

        if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
            socket.close();
            return null;
        }
    }

    if (__remoteVerificationEnabled && !verifyRemote(socket)) {
        InetAddress host1, host2;

        host1 = socket.getInetAddress();
        host2 = getRemoteAddress();

        socket.close();

        throw new IOException("Host attempting data connection " + host1.getHostAddress()
                + " is not same as server " + host2.getHostAddress());
    }

    if (__dataTimeout >= 0)
        socket.setSoTimeout(__dataTimeout);

    return socket;
}

From source file:org.jibble.pircbot.PircBot.java

/**
 * Attempts to establish a DCC CHAT session with a client.  This method
 * issues the connection request to the client and then waits for the
 * client to respond.  If the connection is successfully made, then a
 * DccChat object is returned by this method.  If the connection is not
 * made within the time limit specified by the timeout value, then null
 * is returned./*  w  w w.j a v a 2s. c  o  m*/
 * <p/>
 * It is <b>strongly recommended</b> that you call this method within a new
 * Thread, as it may take a long time to return.
 * <p/>
 * This method may not be overridden.
 *
 * @param nick    The nick of the user we are trying to establish a chat with.
 * @param timeout The number of milliseconds to wait for the recipient to
 *                accept the chat connection (we recommend about 120000).
 * @return a DccChat object that can be used to send and recieve lines of
 * text.  Returns <b>null</b> if the connection could not be made.
 * @see DccChat
 * @since PircBot 0.9.8
 */
public final DccChat dccSendChatRequest(String nick, int timeout) {
    DccChat chat = null;
    try {
        ServerSocket ss = null;

        int[] ports = getDccPorts();
        if (ports == null) {
            // Use any free port.
            ss = new ServerSocket(0);
        } else {
            for (int i = 0; i < ports.length; i++) {
                try {
                    ss = new ServerSocket(ports[i]);
                    // Found a port number we could use.
                    break;
                } catch (Exception e) {
                    // Do nothing; go round and try another port.
                }
            }
            if (ss == null) {
                // No ports could be used.
                throw new IOException("All ports returned by getDccPorts() are in use.");
            }
        }

        ss.setSoTimeout(timeout);
        int port = ss.getLocalPort();

        InetAddress inetAddress = getDccInetAddress();
        if (inetAddress == null) {
            inetAddress = getInetAddress();
        }
        byte[] ip = inetAddress.getAddress();
        long ipNum = ipToLong(ip);

        sendCTCPCommand(nick, "DCC CHAT chat " + ipNum + " " + port);

        // The client may now connect to us to chat.
        Socket socket = ss.accept();

        // Close the server socket now that we've finished with it.
        ss.close();

        chat = new DccChat(this, nick, socket);
    } catch (Exception e) {
        // Do nothing.
    }
    return chat;
}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * Establishes a data connection with the FTP server, returning
 * a Socket for the connection if successful.  If a restart
 * offset has been set with {@link #setRestartOffset(long)},
 * a REST command is issued to the server with the offset as
 * an argument before establishing the data connection.  Active
 * mode connections also cause a local PORT command to be issued.
 * <p>/*from w ww. j a va2s. c o  m*/
 * @param command  The text representation of the FTP command to send.
 * @param arg The arguments to the FTP command.  If this parameter is
 *             set to null, then the command is sent with no argument.
 * @return A Socket corresponding to the established data connection.
 *         Null is returned if an FTP protocol error is reported at
 *         any point during the establishment and initialization of
 *         the connection.
 * @exception IOException  If an I/O error occurs while either sending a
 *      command to the server or receiving a reply from the server.
 * @since 3.1
 */
protected Socket _openDataConnection_(String command, String arg) throws IOException {
    if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE
            && __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE) {
        return null;
    }

    final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address;

    Socket socket;

    if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE) {
        // if no activePortRange was set (correctly) -> getActivePort() = 0
        // -> new ServerSocket(0) -> bind to any free local port
        ServerSocket server = _serverSocketFactory_.createServerSocket(getActivePort(), 1, getHostAddress());

        try {
            // Try EPRT only if remote server is over IPv6, if not use PORT,
            // because EPRT has no advantage over PORT on IPv4.
            // It could even have the disadvantage,
            // that EPRT will make the data connection fail, because
            // today's intelligent NAT Firewalls are able to
            // substitute IP addresses in the PORT command,
            // but might not be able to recognize the EPRT command.
            if (isInet6Address) {
                if (!FTPReply.isPositiveCompletion(eprt(getReportHostAddress(), server.getLocalPort()))) {
                    return null;
                }
            } else {
                if (!FTPReply.isPositiveCompletion(port(getReportHostAddress(), server.getLocalPort()))) {
                    return null;
                }
            }

            if ((__restartOffset > 0) && !restart(__restartOffset)) {
                return null;
            }

            if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
                return null;
            }

            // For now, let's just use the data timeout value for waiting for
            // the data connection.  It may be desirable to let this be a
            // separately configurable value.  In any case, we really want
            // to allow preventing the accept from blocking indefinitely.
            if (__dataTimeout >= 0) {
                server.setSoTimeout(__dataTimeout);
            }
            socket = server.accept();

            // Ensure the timeout is set before any commands are issued on the new socket
            if (__dataTimeout >= 0) {
                socket.setSoTimeout(__dataTimeout);
            }
            if (__receiveDataSocketBufferSize > 0) {
                socket.setReceiveBufferSize(__receiveDataSocketBufferSize);
            }
            if (__sendDataSocketBufferSize > 0) {
                socket.setSendBufferSize(__sendDataSocketBufferSize);
            }
        } finally {
            server.close();
        }
    } else { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE

        // Try EPSV command first on IPv6 - and IPv4 if enabled.
        // When using IPv4 with NAT it has the advantage
        // to work with more rare configurations.
        // E.g. if FTP server has a static PASV address (external network)
        // and the client is coming from another internal network.
        // In that case the data connection after PASV command would fail,
        // while EPSV would make the client succeed by taking just the port.
        boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address;
        if (attemptEPSV && epsv() == FTPReply.ENTERING_EPSV_MODE) {
            _parseExtendedPassiveModeReply(_replyLines.get(0));
        } else {
            if (isInet6Address) {
                return null; // Must use EPSV for IPV6
            }
            // If EPSV failed on IPV4, revert to PASV
            if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) {
                return null;
            }
            _parsePassiveModeReply(_replyLines.get(0));
        }

        socket = _socketFactory_.createSocket();
        if (__receiveDataSocketBufferSize > 0) {
            socket.setReceiveBufferSize(__receiveDataSocketBufferSize);
        }
        if (__sendDataSocketBufferSize > 0) {
            socket.setSendBufferSize(__sendDataSocketBufferSize);
        }
        if (__passiveLocalHost != null) {
            socket.bind(new InetSocketAddress(__passiveLocalHost, 0));
        }

        // For now, let's just use the data timeout value for waiting for
        // the data connection.  It may be desirable to let this be a
        // separately configurable value.  In any case, we really want
        // to allow preventing the accept from blocking indefinitely.
        if (__dataTimeout >= 0) {
            socket.setSoTimeout(__dataTimeout);
        }

        socket.connect(new InetSocketAddress(__passiveHost, __passivePort), connectTimeout);
        if ((__restartOffset > 0) && !restart(__restartOffset)) {
            socket.close();
            return null;
        }

        if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
            socket.close();
            return null;
        }
    }

    if (__remoteVerificationEnabled && !verifyRemote(socket)) {
        socket.close();

        throw new IOException("Host attempting data connection " + socket.getInetAddress().getHostAddress()
                + " is not same as server " + getRemoteAddress().getHostAddress());
    }

    return socket;
}