Consume a WebSocket connection using Scala and Pla

2019-07-04 12:08发布

I'm looking for a way to consume a websocket in Scala.

The websocket is created in a play Application. Here the code in the

controller

def socket = WebSocket.acceptWithActor[String, JsValue] { request => out =>
  WebsocketActor.props(out)
}

routes

# Sockets
GET     /socket                          controllers.MyController.socket

Connecting to the socket using Javascript works fine. Now I want to connect to the socket using a http-Client. At the moment I use the PlayHttpClient

Client sbt dependecy

"com.typesafe.play" %% "play-ws" % "2.3.4"

Code to consume Websocket

I found several methods on the client that might do the trick but I'm lost which one to use and how to use them:

https://www.playframework.com/documentation/2.3.x/api/scala/index.html#play.api.libs.ws.WSRequestHolder

def get[A](consumer: (WSResponseHeaders) ⇒ Iteratee[Array[Byte], A])(implicit ec: ExecutionContext): Future[Iteratee[Array[Byte], A]]

looks like it could do the trick. But how to Implement a Consumer?

def getStream(): Future[(WSResponseHeaders, Enumerator[Array[Byte]])]

// Thats how I used it
  def alertStream = client.
    url(http://localhost:9000/socket).
    withHeaders("Accept" -> "application/json").
    stream.map { case (headers, enumerator) =>
      println(headers)

      val loggingIteratee = Iteratee.foreach[Array[Byte]] { chunk =>
        val chunkString = new String(chunk, "UTF-8")
        println(chunkString)
      }

     enumerator.apply( loggingIteratee )

loggingIteratee.run

}

I tried this one but I get an 400 - Excpetion in the ResponseHeaders all the time. Changing the protocol to ws:// in the url leads to this exeption:

> val con = client.url("ws://localhost:9000/socket").get
java.io.IOException: WebSocket method must be a GET
at    com.ning.http.client.providers.netty.NettyAsyncHttpProvider.doConnect(NettyAsyncHttpProvider.java:989) 

0条回答
登录 后发表回答