Hi,
I’m trying to adopt sttp4
client to interact with a server via WebSockets. WebSockets seems unstable. For example, if the connection drops sttp4
throws exception Caused by: java.io.IOException: Software caused connection abort
. Sometimes exception Caused by: java.io.IOException: Operation timed out
occurs.
I’m using code from an example:
implicit val runtime: IORuntime = cats.effect.unsafe.implicits.global
private def webSocketFramePipe: Pipe[IO, WebSocketFrame.Data[_], WebSocketFrame] = { input =>
Stream.emit(WebSocketFrame.text("""
|{
| "op": "subscribe",
| "args": [
| "topic-name"
| ]
|}
|""".stripMargin)) ++ input.flatMap {
case WebSocketFrame.Text(n, _, _) =>
println(s"received: $n")
Stream.emit(WebSocketFrame.Ping(Array(2)))
case x =>
println("...other...")
Stream.empty // ignoring
}
}
HttpClientFs2Backend
.resource[IO]()
.use { backend =>
basicRequest
.get(uri"wss://stream.server.com/public")
.response(asWebSocketStream(Fs2Streams[IO])(webSocketFramePipe))
.send(backend)
.void
}
.unsafeRunSync()
How can I monitor the state of a websocket? And reconnect it if it fails?
I also tried and found out that sending Stream.empty
in case WebSocketFrame.Text(n, _, _) =>
stops streaming after ~30 frames. But if in send WebSocketFrame.Ping
in response, then the server sends frames infinitely. What proper message should I send in response to case WebSocketFrame.Text(...)=>
?