播放Websocket连接已关闭

Play Websocket connection closed

本文关键字:连接 Websocket 播放      更新时间:2023-09-26

我开始使用webSockets,angular&玩我使用https://github.com/AngularClass/angular-websocket以获得良好的角度积分。这样的连接:

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/nety日志中,我只找到:

 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协议而不是安全的ws协议?应该是这样的:$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"}并搜索的,那么您会得到"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
  }
}

编辑:

这是否来自你必须获得data属性而不是直接获得message的ng-websocket?

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