gpt4 book ai didi

javascript - Play Websocket 连接已关闭

转载 作者:行者123 更新时间:2023-12-03 08:16:13 26 4
gpt4 key购买 nike

我正在开始使用 webSockets、Angular 和 Play。我用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 协议(protocol)而不是安全协议(protocol) (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));
});

关于javascript - Play Websocket 连接已关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33926133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com