Cells/cells/server/src/net/okennedy/cells/WebsocketConnection.scala

73 lines
1.8 KiB
Scala

package net.okennedy.cells
import scala.collection.concurrent
import cask.endpoints.WsChannelActor
import cask.util.Ws
import java.util.concurrent.atomic.AtomicInteger
import net.okennedy.cells._
import play.api.libs.json.Json
class WebsocketConnection(val id: Int, channel: WsChannelActor)
{
def handle(event: Ws.Event): Unit =
{
event match {
case Ws.Text(data) =>
// println(s"ZZZ: $data")
Json.parse(data).as[WebsocketRequest] match {
case WebsocketHello(_) =>
for(table <- CellsServer.layout.tables.values)
{
send(AddTable(table.serialize))
}
case op: CanvasRequest =>
CellsServer.layout.update(op)
}
case Ws.Error(err) =>
println(s"Websocket $id Error: ${err.getMessage()}")
// WebsocketConnection.allConnect?ions.remove(id)
case Ws.ChannelClosed() =>
/* Close is invoked as well */
case Ws.Close(code, reason) =>
println(s"Websocket $id Closed")
WebsocketConnection.allConnections.remove(id)
case Ws.Ping(value) =>
println("ping")
channel.send(Ws.Pong(value))
}
}
def send(msg: WebsocketResponse): Unit =
{
// println(s"Sending from $id")
channel.send(
cask.Ws.Text(
Json.toJson(msg).toString
)
)
}
}
object WebsocketConnection
{
var nextId = AtomicInteger(0)
val allConnections = concurrent.TrieMap[Int, WebsocketConnection]()
def connect(channel: WsChannelActor): WebsocketConnection =
{
val connection = new WebsocketConnection(nextId.addAndGet(1), channel)
allConnections.put(connection.id, connection)
return connection
}
def broadcast(msg: WebsocketResponse): Unit =
{
allConnections.values.foreach { _.send(msg) }
}
}