如何关闭 WebSocket 连接?如果要立即关闭文档,则文档上的示例有效。
但是以下情况怎么样:我想在将来发生某些情况时关闭连接。例如,当我收到来自客户端的某条消息时。
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)
}
}
感谢您的帮助!
我明白了:我必须通过我打开的频道
var outEnumerator: Enumerator[String] = Concurrent.unicast(c => channel = Some(c))
并且注释掉的块将变为
if (gotString == "close_me") {
channel.foreach(_.eofAndEnd())
}
这将通过枚举器推送 EOF 并关闭连接。