List of usage examples for java.net Socket setSoTimeout
public synchronized void setSoTimeout(int timeout) throws SocketException
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 w w . ja v a2 s .com * @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; }
From source file:org.jibble.pircbot.PircBot.java
/** * Attempt to connect to the specified IRC server using the supplied * password.//from w w w . java 2 s . co m * The onConnect method is called upon success. * * @param hostname The hostname of the server to connect to. * @param port The port number to connect to on the server. * @param password The password to use to join the server. * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public final synchronized void connect(String hostname, int port, String password) throws IOException, IrcException, NickAlreadyInUseException { _server = hostname; _port = port; _password = password; if (isConnected()) { throw new IOException("The PircBot is already connected to an IRC server. Disconnect first."); } // Don't clear the outqueue - there might be something important in it! // Clear everything we may have know about channels. this.removeAllChannels(); // Connect to the server. Socket socket = new Socket(hostname, port); logger.info("*** Connected to server."); _inetAddress = socket.getLocalAddress(); _detector = new UniversalDetector(null); String defaultEncoding = null; OutputStreamWriter outputStreamWriter = null; if (getEncoding() != null) { // Assume the specified encoding is valid for this JVM. outputStreamWriter = new OutputStreamWriter(socket.getOutputStream(), getEncoding()); } else { // Otherwise, just use the JVM's default encoding. outputStreamWriter = new OutputStreamWriter(socket.getOutputStream()); } defaultEncoding = outputStreamWriter.getEncoding(); BufferedWriter bwriter = new BufferedWriter(outputStreamWriter); // Attempt to join the server. if (password != null && !password.equals("")) { OutputThread.sendRawLine(this, bwriter, "PASS " + password); } String nick = this.getName(); OutputThread.sendRawLine(this, bwriter, "NICK " + nick); OutputThread.sendRawLine(this, bwriter, "USER " + this.getLogin() + " 8 * :" + this.getVersion()); _inputThread = new InputThread(this, socket, socket.getInputStream(), bwriter, defaultEncoding); boolean connected = false; // Read stuff back from the server to see if we connected. int tries = 1; byte[] buffer = new byte[BUFFER_SIZE]; int readBytes = -1; String overflow = ""; while ((readBytes = socket.getInputStream().read(buffer)) > -1) { String encoding = detect(buffer); if (logger.isDebugEnabled()) { logger.debug("Detected encoding from IRC Server: {} (may be null)", encoding); } if (StringUtils.isBlank(encoding)) { encoding = defaultEncoding; } String decodedBuffer = new String(buffer, 0, readBytes, Charset.forName(encoding)); String[] lines = (overflow + decodedBuffer).split("\\r?\\n"); // if the buffer does not end with a \n, then maybe the last sentence is not complete // We need to save this part for the next round. if (!decodedBuffer.endsWith("\n")) { overflow = lines[lines.length - 1]; lines = ArrayUtils.remove(lines, lines.length - 1); } else { overflow = ""; } for (String line : lines) { if (StringUtils.isNotBlank(line)) { this.handleLine(line); int firstSpace = line.indexOf(" "); int secondSpace = line.indexOf(" ", firstSpace + 1); if (secondSpace >= 0) { String code = line.substring(firstSpace + 1, secondSpace); if (code.equals("004")) { // We're connected to the server. connected = true; break; } else if (code.equals("433")) { if (_autoNickChange) { tries++; nick = getName() + tries; OutputThread.sendRawLine(this, bwriter, "NICK " + nick); } else { socket.close(); _inputThread = null; throw new NickAlreadyInUseException(line); } } else if (code.equals("439")) { // No action required. } else if (code.startsWith("5") || code.startsWith("4")) { socket.close(); _inputThread = null; throw new IrcException("Could not log into the IRC server: " + line); } } this.setNick(nick); } } if (connected) { break; } } logger.info("*** Logged onto server."); // This makes the socket timeout on read operations after 5 minutes. // Maybe in some future version I will let the user change this at runtime. socket.setSoTimeout(5 * 60 * 1000); // Now start the InputThread to read all other lines from the server. _inputThread.start(); // Now start the outputThread that will be used to send all messages. if (_outputThread == null) { _outputThread = new OutputThread(this, _outQueue); _outputThread.start(); } this.onConnect(); }