使用Akka IO在Tcp客户端上发送非ByteString

时间:2017-05-10 16:19:21

标签: scala sockets tcp akka akka-io

我正在使用akka-io创建一个Tcp Client Actor,它通过套接字与非jvm tcp(非akka)服务器通信。由于akka-io发送ByteString并且程序期望向其输出常规String,因此永远不会处理ByteString消息。一个非常粗略的基于Java的方法实际工作

override def receive: Receive = {
    case ClientTcpActor.Start =>
      val socket = new Socket(socketAddress.getHostName, socketAddress.getPort)
      val out = new PrintWriter(socket.getOutputStream, true)
      out.println("Hello World!")
      import java.io.BufferedReader
      import java.io.InputStreamReader
      val is = socket.getInputStream
      val isr = new InputStreamReader(is)
      val br = new BufferedReader(isr)
      val message = br.readLine
      println(s"Message received from the server : $message")
}

我能够向tcp端口发送消息并收到回复消息。

但是,这种akka-io方法不起作用。具体来说,我从未从套接字接收数据,因为外部应用程序无法处理ByteString对象发送的Write

def receive: PartialFunction[Any, Unit] = {
    case CommandFailed(_: Connect) =>
      log.info("Connection failed.")
      context stop self

    case c@Connected(_, _) =>
      log.info("Connect succeeded.")
      val connection = sender()
      connection ! Register(self)
      val message = ByteString("hello world")
      log.info(s"Sending request message ${message}")
      connection ! Write(message)

    case Received(data) =>
      log.info(data.toString())


    case _: ConnectionClosed =>
      log.info("Connected is closed!")
    case _ =>
      log.info("Something else is up.")
  }

我还创建了自己的akka​​-IO服务器应用程序,该应用程序处理同一端口上的数据并验证我实际上是将消息发送到端口,但是需要akka服务器actor来处理{{1}的解码}

我希望这是一个容易解决的问题,我忽视了。

0 个答案:

没有答案