如何关闭WebSocket连接? documentation上的示例可以立即关闭。
但是以下情况怎么样:我想在将来发生某种情况时关闭连接。例如,当我收到客户的某条消息时。
def indexWS = WebSocket.using[String] {
request => {
var channel: Option[Concurrent.Channel[String]] = None
var outEnumerator: Enumerator[String] = Concurrent.unicast(c => channel = Some(c))
val myIteratee: Iteratee[String, Unit] = Iteratee.foreach[String] {gotString => {
// received a string from the client
if (gotString == "close_me") {
// outEnumerator = Enumerator.eof // doesn't work
// outEnumerator >>> Enumerator.eof // doesn't work
}
}}
(myIteratee, outEnumerator)
}
}
感谢您的帮助!
答案 0 :(得分:3)
我明白了:我必须通过我在
打开的频道var outEnumerator: Enumerator[String] = Concurrent.unicast(c => channel = Some(c))
,注释掉的区块将成为
if (gotString == "close_me") {
channel.foreach(_.eofAndEnd())
}
将通过枚举器推送EOF并关闭连接。