Class Socket

java.lang.Object
dev.gmitch215.bytebox.socket.Socket
All Implemented Interfaces:
AutoCloseable

public final class Socket extends Object implements AutoCloseable
One TCP connection.

Reads and writes block. Closing is what releases the connection, and the six-simultaneous- connection limit every plan has makes that matter: a socket left open holds a sixth of the invocation's budget. This is AutoCloseable so try-with-resources can do it.

 try (Socket socket = Sockets.connectTLS("example.com", 443)) {
 	socket.write("GET / HTTP/1.0\r\nHost: example.com\r\n\r\n");
 	System.out.println(socket.readAll());
 }
Since:
1.0.0
  • Method Details

    • write

      public void write(String text)
      Writes text, UTF-8 encoded.

      The text is held and sent with the next call that reads, upgrades, closes or waits on the socket, with flush(), or once 64 Ki characters are held, so a dialogue of short lines costs one write per exchange rather than one per line and a large upload never sits whole in memory. A write that fails is reported by that later call (or by this one, at the cap).

      Parameters:
      text - the text
    • flush

      public void flush()
      Sends whatever write(String) is holding.
    • read

      public String read()
      Reads whatever has arrived, up to the next chunk boundary.
      Returns:
      the text, or null at end of stream
    • readAll

      public String readAll()
      Reads until the peer closes the connection.
      Returns:
      everything that arrived
    • readUntil

      public String readUntil(String delimiter)
      Reads until a delimiter appears, which is how a line-oriented protocol is framed.
      Parameters:
      delimiter - the delimiter, such as "\r\n"
      Returns:
      the text up to but not including the delimiter, or null at end of stream
    • startTLS

      public Socket startTLS()
      Upgrades a connection opened with Sockets.connectStartTLS(String, int) to TLS.

      Returns a new socket. The original is unusable afterwards, which is why the result has to be kept rather than discarded.

      Returns:
      the encrypted socket
    • closed

      public org.teavm.jso.core.JSPromise<org.teavm.jso.JSObject> closed()
      Returns a promise that settles when the connection closes, for ctx.waitUntil.
      Returns:
      a promise that settles when the connection closes, for ctx.waitUntil
    • unwrap

      public org.teavm.jso.JSObject unwrap()
      Returns the platform's own socket object, for anything this surface does not cover.

      Held writes are sent first, so what is written through the object follows them.

      Returns:
      the platform's own socket object, for anything this surface does not cover
    • close

      public void close()
      Specified by:
      close in interface AutoCloseable