Sunday, October 5, 2014

Server Side WebSocket in Java



I recently wrote a high quality, low grade, server side WebSocket (RFC 6455) implementation. The intended use-case is as follows:
  • I want to create a service in Java that accepts connections from modern web browsers.
  • I want to use InputStream and OutputStream to get my bytes back and forth between my service and the browser.
  • I want my service code to do this with minimal setup.
  • I want to ignore all the protocol details; just give me the bytes.
  • I'm not sure, but I might like to support SSL/TLS security (i.e.: HTTPS) for none/some/all of my connections.

 

Need More?


If you need something else, like Java NIO support, non-blocking I/O, evented I/O, ability to provide custom handlers for web frames, etc.. then you'll probably need to find another implementation:
Note that JavaEE 7 includes WebSocket support. So if you've already got a web container (i.e.: Tomcat), then you've probably already got a solution at hand:


 

Just Enough


Since you're still reading this, I'll assume you want to know more about my WebSocket implementation. You can find the repository here:

https://github.com/blinkdog/websocket

How does it work? I'm glad you asked...


This is how you start listening for WebSocket connections:
ServerSocket serverSocket = new ServerSocket(PORT);
WebSocketServerSocket webSocketServerSocket = new WebSocketServerSocket(serverSocket);
WebSocket webSocket = webSocketServerSocket.accept();

And this is how you read data from the connecting client:
InputStream is = webSocket.getInputStream();
int data = is.read();

And this is how you communicate back to the connecting client:
WebSocketServerOutputStream os = webSocket.getOutputStream();
os.writeString("This is a UTF-8 string.");
os.writeBinary("Some binary data.".getBytes()); 


That's It

A high quality, low grade, server-side WebSocket component with no frills or nonsense. That's it, that's all. Enjoy!

2 comments: