1

我正在使用 Vert.x Scala 库(版本 3.8.0),但我不知道如何设置 websocket 连接并发送消息。按照 Vert.x 3.5.4 的文档说明,这应该可以工作:

import io.vertx.scala.core.Vertx
import io.vertx.scala.core.http.HttpClientOptions

object WsClient extends App {
  val vertx = Vertx.vertx
  val client = vertx.createHttpClient

  client.websocket(8080, "localhost", "/api", (ws: io.vertx.scala.core.http.WebSocket) => {
    println("connected")
    val message = "hello"
    ws.writeTextMessage(message)
  })
}

但是在编译时会抛出以下错误:

Error:(9, 10) overloaded method value websocket with alternatives:
  (requestURI: String,headers: io.vertx.scala.core.MultiMap,version: io.vertx.core.http.WebsocketVersion,wsConnect: io.vertx.core.Handler[io.vertx.scala.core.http.WebSocket])io.vertx.scala.core.http.HttpClient <and>
  (requestURI: String,headers: io.vertx.scala.core.MultiMap,wsConnect: io.vertx.core.Handler[io.vertx.scala.core.http.WebSocket],failureHandler: io.vertx.core.Handler[Throwable])io.vertx.scala.core.http.HttpClient <and>
  (options: io.vertx.scala.core.http.RequestOptions,headers: io.vertx.scala.core.MultiMap,version: io.vertx.core.http.WebsocketVersion,wsConnect: io.vertx.core.Handler[io.vertx.scala.core.http.WebSocket])io.vertx.scala.core.http.HttpClient <and>
  (host: String,requestURI: String,headers: io.vertx.scala.core.MultiMap,wsConnect: io.vertx.core.Handler[io.vertx.scala.core.http.WebSocket])io.vertx.scala.core.http.HttpClient <and>
  (options: io.vertx.scala.core.http.RequestOptions,headers: io.vertx.scala.core.MultiMap,wsConnect: io.vertx.core.Handler[io.vertx.scala.core.http.WebSocket],failureHandler: io.vertx.core.Handler[Throwable])io.vertx.scala.core.http.HttpClient <and>
  (host: String,requestURI: String,wsConnect: io.vertx.core.Handler[io.vertx.scala.core.http.WebSocket],failureHandler: io.vertx.core.Handler[Throwable])io.vertx.scala.core.http.HttpClient <and>
  (port: Int,host: String,requestURI: String,wsConnect: io.vertx.core.Handler[io.vertx.scala.core.http.WebSocket])io.vertx.scala.core.http.HttpClient
 cannot be applied to (Int, String, String, io.vertx.scala.core.http.WebSocket => io.vertx.scala.core.http.WebSocket)
  client.websocket(8080, "localhost", "/api", (ws: io.vertx.scala.core.http.WebSocket) => {

我也尝试让语言推断处理程序类型,但没有成功。我究竟做错了什么?

4

1 回答 1

0

查看 java doc 我注意到 API 发生了变化,该方法client.websocket(...)已弃用,应该使用的方法是client.webSocket(...).

这是上面代码的更正版本,它应该从 Vert.x 3.6.x 版本开始工作:

import io.vertx.core.AsyncResult
import io.vertx.scala.core.http.WebSocket

client.webSocket(8080, "localhost", "/api", (res: AsyncResult[WebSocket]) => {
  if (res.succeeded) {
    println("connected")
    val ws = res.result()
    val message = "hello"
    ws.writeTextMessage(message)
  } else {
    println(res.cause)
  }
})
于 2019-12-10T21:37:55.603 回答