使用http4s打开Websocket连接

时间:2018-03-20 19:14:38

标签: scala websocket http4s

我正在运行http4s WS示例: https://github.com/http4s/http4s/blob/master/examples/blaze/src/main/scala/com/example/http4s/blaze/BlazeWebSocketExample.scala

我正在尝试通过Google Chrome控制台连接到它:

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)

我想念什么?

1 个答案:

答案 0 :(得分:4)

您只是不等到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)