Interface SocketObject

All Superinterfaces:
DurableObject

public interface SocketObject extends DurableObject
A Durable Object that takes WebSockets.

The only way several clients reach the same object at once, and the only inbound connection a Worker can hold open. Accept one in DurableObject.fetch(dev.gmitch215.bytebox.Request, dev.gmitch215.bytebox.durable.DurableState, dev.gmitch215.bytebox.Env) and the messages arrive here.

 @Override
 public Response fetch(Request request, DurableState state, Env env) {
 	WebSocketPair pair = WebSocketPair.create();
 	state.acceptWebSocket(pair.server());
 	return Bytebox.upgrade(pair.client());
 }

 @Override
 public void message(WebSocket socket, String text, DurableState state, Env env) {
 	state.broadcast(text);
 }

Accepting through DurableState.acceptWebSocket(dev.gmitch215.bytebox.socket.WebSocket) lets the instance hibernate: the connection stays open with no instance in memory, and the next message builds one again. So the instance's fields may be empty when a message arrives even though the connection is old, and per-connection state belongs on the connection through WebSocket.attach(dev.gmitch215.bytebox.js.TSObject).

Since:
1.0.0
  • Method Details

    • message

      void message(WebSocket socket, String text, DurableState state, Env env)
      A text message arrived.
      Parameters:
      socket - which connection sent it
      text - the message
      state - this instance's storage, alarm and sockets
      env - the bindings
    • message

      default void message(WebSocket socket, byte[] bytes, DurableState state, Env env)
      A binary message arrived.

      The default reads it as UTF-8 and hands it to message(dev.gmitch215.bytebox.socket.WebSocket, java.lang.String, dev.gmitch215.bytebox.durable.DurableState, dev.gmitch215.bytebox.Env), which is right for a protocol that is text in a binary frame and wrong for one that is not.

      Parameters:
      socket - which connection sent it
      bytes - the message
      state - this instance's storage, alarm and sockets
      env - the bindings
    • closed

      default void closed(WebSocket socket, int code, String reason, boolean clean, DurableState state, Env env)
      A connection closed.
      Parameters:
      socket - which connection
      code - the close code
      reason - the close reason
      clean - whether the peer closed properly
      state - this instance's storage, alarm and sockets
      env - the bindings
    • failed

      default void failed(WebSocket socket, String message, DurableState state, Env env)
      A connection failed.
      Parameters:
      socket - which connection
      message - what went wrong
      state - this instance's storage, alarm and sockets
      env - the bindings