Sample code for 30+ languages & platforms
Java

Receive a Bounded String from a Socket

See more Socket/SSL/TLS Examples

Demonstrates Socket.ReceiveStringMaxN, which receives and decodes text like ReceiveString but reads at most a given number of input bytes.

Background. The limit is measured in bytes, not Unicode characters, so a byte limit can split a multibyte character or a protocol token. Decoding uses StringCharset.

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.  The 3rd argument enables the TLS handshake after the TCP
        // connection succeeds; the 4th is the maximum time to wait, in milliseconds.
        boolean bTls = true;
        int maxWaitMs = 5000;
        try {
            socket.connect("example.com", 5000, bTls, maxWaitMs);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // StringCharset controls the character encoding used when sending and receiving text.
        socket.setStringCharset("utf-8");
        // Send a request using a simple application-defined text protocol in which each message ends with a
        // CRLF.
        String command = "STATUS\r\n";
        String firstChunk;
        try {
            socket.sendString(command);

            // Receive and decode text like ReceiveString, but read at most the given number of input bytes.
            // The limit is measured in bytes, not Unicode characters.
            firstChunk = socket.receiveStringMaxN(64);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println(firstChunk);
    }
}