WebSockets in Resin
WebSockets is an IETF specification designed to enable more truly interactive browser applications. It creates a message-based system over TCP, after upgrading from a HTTP request. The messages to and from the browser allow for server-sent events and asynchronous notifications. Think of it as a clean implementation of Comet.
The first applications will likely be simple chat improvements, and will become more sophisticated. Google has already demonstrated a Quake implementation.
Resin’s WebSockets API is designed around streams and messages. Each WebSocket message is a traditional Java stream. The message ends when the stream ends.
Your applications receives messages from a listener, because messages are asynchronous and because Resin wants to save threads when no activity is occurring. When your listener finishes Resin will send the next message:
public interface WebSocketListener { public void onReadBinary(WebSocketContext context, InputStream is) throws IOException; public void onReadText(WebSocketContext context, Reader is) throws IOException; }
You’ll want to read the messages quickly and hand them off, because the next message will wait until you’re done with the current message.
Sending messages is also stream-based. Your application starts a new message with a startBinaryMessage() or startTextMessage() call, writes to the OutputStream or PrintWriter, and closes it when the message completes.
public interface WebSocketContext {
public OutputStream startBinaryMessage()
throws IOException;
public PrintWriter startTextMessage()
throws IOException;
}
Again, you’ll want to write the message quickly because the next message will wait until the current one finishes.
