Accept WebSocket Connections
Similar to regular Site
s that respond to HTTP requests, you can add WebSocketSite
s that handle WebSocket connections.
@AppType(name = "wsecho")
public class EchoWebSocketApp extends App {
@Override
public void start() {
SiteLocation location = getConfig().getLocation("location").orError();
addWebSocketSite(location, websocket -> {
// Accept or immediately close
HTTPRequest initreq = websocket.getHTTPRequest();
String name = initreq.getQuery("name");
if (name == null) {
websocket.close(1008, "Please provide a name");
return;
}
websocket.accept();
// Lifecycle
while (true) {
String message = websocket.receiveText(); // may throw WebSocketCloseException
if (message.equals("close"))
break;
websocket.sendText(name + ": " + message);
}
// Close
websocket.close();
});
}
}
WebSocket
s resemble standard synchronous Java Socket
s, but with extra methods specific to WebSockets.
While you may choose to use the thread calling your WebSocketSite
for the lifetime of the websocket (and longer), you also may (and typicall will) keep and use the websocket in other threads.
That is fine, but mind to always call either accept()
or close()
directly in the WebSocketSite
s handling method, as the server will interpret doing neither as the WebSocket connection remaining unhandled by the WebSocketSite, which would prohibit you from using it anymore.
While WebSocket.accept()
is called automatically when using other WebSocket methods, like receiveText
or sendText
as in the example above, I recommend calling it explicity.