gpt4 book ai didi

scala - 使用 http4s 打开 Websocket 连接

转载 作者:行者123 更新时间:2023-12-02 17:10:44 25 4
gpt4 key购买 nike

我正在运行来自以下网址的 http4s WS 示例: https://github.com/http4s/http4s/blob/master/examples/blaze/src/main/scala/com/example/http4s/blaze/BlazeWebSocketExample.scala

我正在尝试从谷歌浏览器控制台连接到它:

var ws = new WebSocket("ws://localhost:8080/http4s/wsecho")
ws.send("Hi")

但实际上我没有看到消息。在控制台日志中,我看到了

Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
at <anonymous>:1:4
(anonymous) @ VM204:1
VM186:1 WebSocket connection to 'ws://localhost:8080/http4s/wsecho' failed: Connection closed before receiving a handshake response

并且服务器日志没有错误:

23:12:43 [blaze-nio1-acceptor] INFO  o.h.blaze.channel.ServerChannelGroup - Connection to /127.0.0.1:59777 accepted at Tue Mar 20 23:12:43 GST 2018.
23:12:43 [blaze-nio-fixed-selector-pool-3] DEBUG org.http4s.blaze.pipeline.Stage - SocketChannelHead starting up at Tue Mar 20 23:12:43 GST 2018
23:12:43 [blaze-nio-fixed-selector-pool-3] DEBUG org.http4s.blaze.pipeline.Stage - Stage SocketChannelHead sending inbound command: Connected
23:12:43 [blaze-nio-fixed-selector-pool-3] DEBUG org.http4s.blaze.pipeline.Stage - QuietTimeoutStage starting up at Tue Mar 20 23:12:43 GST 2018
23:12:43 [blaze-nio-fixed-selector-pool-3] DEBUG org.http4s.blaze.pipeline.Stage - Stage QuietTimeoutStage sending inbound command: Connected
23:12:43 [blaze-nio-fixed-selector-pool-3] DEBUG org.http4s.blaze.pipeline.Stage - Starting HTTP pipeline
23:12:43 [blaze-nio-fixed-selector-pool-3] DEBUG o.h.blaze.channel.nio1.SelectorLoop - Started channel.
23:12:43 [scala-execution-context-global-19] DEBUG org.http4s.blaze.pipeline.Stage - Websocket key: Some(WebSocketContext(Websocket(Stream(..),fs2.async.mutable.Queue$$Lambda$378/1284896246@5b314a6c),Headers(),IO$1816945727))
Request headers: Headers(Host: localhost:8080, Connection: Upgrade, Pragma: no-cache, Cache-Control: no-cache, Upgrade: websocket, Origin: https://www.google.ae, Sec-WebSocket-Version: 13, User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36, Accept-Encoding: gzip, deflate, br, Accept-Language: en-US,en;q=0.9, Cookie: _ga=GA1.1.1008064719.1515165520, Sec-WebSocket-Key: ozUxsxBzUk0MaQwHbk45ow==, Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits)

我错过了什么?

最佳答案

您无需等到 websocket 连接实际打开。试试这个:

var ws = new WebSocket("ws://localhost:8080/http4s/wsecho")
ws.onopen = function(e) { ws.send("Hi") }

如果需要,您可以将 WebSocketBuilder 定义更改为此,以便您更清楚地了解正在发送的内容:

WebSocketBuilder[F].build(d.observe1(wsf => F.delay{print(wsf)}), e)

关于scala - 使用 http4s 打开 Websocket 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49392453/

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