This is a minimal example for a websocket that pushes events to a client.
Start by running sbt:
$ sbt run
...
[info] Running Main
Listening on 0:0:0:0:0:0:0:0:8080.
Now, start a websocket-client, for example wsc:
$ wsc ws://127.0.0.1:8080/ws
Connected to ws://127.0.0.1:8080/ws
You can now start typing in the (first) console and receive messages in the second one:
Input an empty line to quit.
The code consists of two objects:
Main
creates the/ws
route, binds it toWebSocket.listen()
, starts the server and listens on StdIn for messages to send toWebsocket.sendText()
.WebSocket
provides alisten
function to register a new listener (orbrowserConnection
) and asendText
function to send a message to every registered connection. The trick here is, thatbrowserConnection
stores a list of functions that can be called later. These functions are theoffer
functions on aQueue
that sends them to the websocket.