Sample code for 30+ languages & platforms
Java

Wait for a Socket to Become Readable

See more Socket/SSL/TLS Examples

Demonstrates Socket.SelectForReading, which waits for read-ready activity on the socket, or on any contained socket when the object is a socket set. It returns 1 if ready, 0 on timeout, or -1 on error.

Background. A timeoutMs of 0 performs a nonblocking poll. With a socket set, this monitors many connections at once for readability.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Socket;

public class ChilkatExample {

    public static void main(String[] args) {
        Socket socket = new Socket();

        // Connect to the server using TLS.
        boolean bTls = true;
        int maxWaitMs = 5000;
        try {
            socket.connect("example.com", 5000, bTls, maxWaitMs);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Wait up to 5 seconds for read-ready activity on the socket (or, for a socket set, on any contained
        // socket).  Returns 1 if ready, 0 on timeout, or -1 on error.
        int ready = socket.selectForReading(5000);
        if (ready < 0) {
            System.out.println(socket.getLastErrorText());
            return;
        }

        if (ready != 1) {
            System.out.println("No data became available before the timeout.");
            return;
        }

        System.out.println("The socket has data ready to read.");
    }
}