播放 Websocket 连接已关闭

Play Websocket connection closed

我开始使用 webSockets,angular 开始玩了。我使用 https://github.com/AngularClass/angular-websocket 进行很好的 angular 集成。这样的连接:

var dataStream = $websocket('wss://echo.websocket.org/');

效果很好。但是尝试连接到:

var dataStream = $websocket('wss://localhost:9000/socket');

结果:

WebSocket connection to 'wss://localhost:9000/socket' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED

在play/netty日志中我只找到:

 play.core.server.netty.PlayDefaultUpstreamHandler - Exception caught in Netty
java.lang.IllegalArgumentException: empty text 

这是我在后端使用的代码:

def socket = WebSocket.acceptWithActor[String, String] { request => out =>
    MyWebSocketActor.props(out)
  }
object MyWebSocketActor {
  def props(out: ActorRef) = Props(new MyWebSocketActor(out))
}
class MyWebSocketActor(out: ActorRef) extends Actor {
  def receive = {
    case msg: String =>
      out ! ("I received your message: " + msg)
  }
}

(基于:https://www.playframework.com/documentation/2.4.x/ScalaWebSockets

这是我的代码: https://github.com/dataplayground/playground/blob/master/public/javascripts/main.js

如我的评论所述:

  1. 您是否尝试过使用普通 ws 协议而不是安全协议 (wss)?它应该是这样的:$websocket('ws://localhost:9000/socket')

  2. 您已经定义了一个处理 [String, String] 的 actor,但实际上您在 Angular 部分中使用了 JSON。两者实际上应该匹配,所以尝试:WebSocket.acceptWithActor[JsValue, JsValue]

我不太确定您返回的 JSON 数据是否正确,也不确定您 Angular 方面的处理方式。

首先,如果您使用反斜杠 \ 方法 (https://www.playframework.com/documentation/2.3.x/api/scala/index.html#play.api.libs.json.JsValue),您会得到一个 JsValue,但这不一定代表有效的 JSON。如果您有 {"foo": "test"} 并搜索 for ,那么您会得到 "test" 但这并不是真正有效的 JSON.

为了获得快速反馈:尝试将 Websocket Actor 更改为 [JsValue, String] 类型,或者您可以在 Actor 中构造一个新的 JsValue:

class MyWebSocketActor(out: ActorRef) extends Actor {
  def receive = {
    case msg: JsValue =>
      Logger.debug("actor something  " + out)
      Logger.debug("message  " + Json.prettyPrint(msg))

      val json: JsValue = Json.parse("""
      {
          "fooReply" : "Something"
      }
      """)
      out ! json
  }
}

编辑:

这是否来自 ng-websocket,您必须获取 data 属性 而不是直接获取 message

dataStream.onMessage(function (message) {
    collection.push(JSON.parse(message.data));
});