-
Notifications
You must be signed in to change notification settings - Fork 46
Require a method to know when a websocket is ready to send message back to client #41
Copy link
Copy link
Closed
Milestone
Description
When the web socket server want to send message to client immediately after connected, RequestHandler will throw exception, see code below:
import org.mashupbots.socko.webserver._
import org.mashupbots.socko.routes._
import org.mashupbots.socko.events._
import org.mashupbots.socko.handlers._
import akka.actor._
import akka.util.duration._
object Main extends App {
val actorSystem = ActorSystem("socko-t1")
val log = akka.event.Logging.getLogger(actorSystem, this)
val routes = Routes({
case HttpRequest(httpRequest) ⇒ httpRequest match {
case _ ⇒ httpRequest.response.write(HttpResponseStatus.NOT_FOUND)
}
case event @ Path("/") ⇒ event match {
case e: WebSocketHandshakeEvent ⇒ {
e.authorize()
val b = actorSystem.actorOf(Props[WebSocketBroadcaster])
b ! WebSocketBroadcasterRegistration(e)
b ! WebSocketBroadcastText("test message")
}
case e: WebSocketFrameEvent ⇒ {
log.debug("get event {}", e)
}
}
})
val webServer = new WebServer(
WebServerConfig(port = 12345),
routes, actorSystem
)
webServer.start()
Runtime.getRuntime.addShutdownHook(new Thread {
override def run { webServer.stop() }
})
}
but send the message later is ok:
import org.mashupbots.socko.webserver._
import org.mashupbots.socko.routes._
import org.mashupbots.socko.events._
import org.mashupbots.socko.handlers._
import akka.actor._
import akka.util.duration._
object Main extends App {
val actorSystem = ActorSystem("socko-t1")
val log = akka.event.Logging.getLogger(actorSystem, this)
val routes = Routes({
case HttpRequest(httpRequest) ⇒ httpRequest match {
case _ ⇒ httpRequest.response.write(HttpResponseStatus.NOT_FOUND)
}
case event @ Path("/") ⇒ event match {
case e: WebSocketHandshakeEvent ⇒ {
e.authorize()
actorSystem.scheduler.scheduleOnce(1 milliseconds) {
val b = actorSystem.actorOf(Props[WebSocketBroadcaster])
b ! WebSocketBroadcasterRegistration(e)
b ! WebSocketBroadcastText("test message")
}
}
case e: WebSocketFrameEvent ⇒ {
log.debug("get event {}", e)
}
}
})
val webServer = new WebServer(
WebServerConfig(port = 12345),
routes, actorSystem
)
webServer.start()
Runtime.getRuntime.addShutdownHook(new Thread {
override def run { webServer.stop() }
})
}I believe that this is because the WebSocket is not ready to send message back when handling WebSocketHandshakeEvent, and after 1ms, the initialize work is finished, and it's ok to send message. But there is no easy way(or obvious way) to know whether the WebSocket is ready to send message back to client now and I can not find how to call some code when the WebSocket is ready.
I think we can generate an event or call some callback function just after doWebSocketHandshake in messageReceived method of RequestHandler to solve the problem.
Reactions are currently unavailable