【发布时间】:2015-08-20 08:40:44
【问题描述】:
Akka 有什么方法可以像 Erlang 中的 {packet,4} 一样实现数据包帧吗? 数据包看起来像这样:
4 bytes length in big endian | body...
例如:
00 00 00 05 H E L L O 0 0 0 5 W O R L D
将是两个数据包“HELLO”和“WORLD”,但它们作为一个接收。
或者
00 00 00 05 H E L L
现在 Akka 接收到这 8 个字节,但还缺少一个,它将在下一次调用“receive”时接收
问题是我的演员的接收总是通过部分或全部请求调用,但我只想在接收中获取“正文”部分,并且只有当它完全接收时。
所以所有需要的是它首先读取这 4 个字节,然后等待直到它读取其他 N 个字节(N = 4 字节标头中的长度),然后它向我的演员发送消息。有没有可能?
我的服务器代码:
import java.net.InetSocketAddress
import akka.actor.{Props, Actor}
import akka.io.Tcp.Bind
import akka.io.{IO, Tcp}
class Server extends Actor{
import context.system
import Tcp._
IO(Tcp) ! Bind(self, new InetSocketAddress("0.0.0.0", 1234))
def receive ={
case bound @ Bound(localAddr) =>
println("Server is bound to "+localAddr.toString())
case failed @ CommandFailed(_ : Bind) =>
context stop self
case connected @ Connected(remote, local) =>
val handler = context.actorOf(Props[ClientHandler])
val connection = sender()
println(remote.toString + "connected to "+local.toString())
connection ! Register(handler)
}
}
【问题讨论】: