問題描述
Akka TCP 客戶端:如何使用 akka actor 通過 TCP 發送消息 (Akka TCP client: How can I send a message over TCP using akka actor)
我想通過 TCP 發送文本消息。相當容易。我想用akka這樣做。我讀了這篇關於 akka IO 的文章:http://doc.akka .io/docs/akka/snapshot/scala/io‑tcp.html
這篇文章介紹了一個 TCP 客戶端的簡單實現,但我不清楚如何使用這個客戶端.
構造函數接受一個 InetSocketAddress 和一個 ActorRef。InetSocketAddress 是有道理的(我假設這是目的地)但是 ActorRef 是什麼?這是我第一次使用akka,但據我了解,ActorRef 是另一個演員的參考。由於我的 TCP 客戶端是一個參與者,並且我希望這個 TCP 參與者與 TCP 服務器通信,不是和其他演員一起,我為什麼要給它一個演員參考?
伴生對像中的道具功能是什麼?
- < p>一旦實例化,我將如何使用這個 actor 發送 TCP 消息?我是否應該只向它發送一條帶有我想要以字節串形式發送的數據的消息?
4. 之間有什麼聯繫/區別
case Received(data) =>
listener ! data
和
case data: ByteString =>
connection ! Write(data)
## 參考解法 #### 方法 1:
Answering your questions:
- The constructor
class Client(remote: InetSocketAddress, listener: ActorRef) extends Actor
takes alistener
which is a reference to an actor that is using thisClient
to communicate with remote server. Listener will send and receive messages through thisClient
. SinceClient
is an actor you will communicate with it solely by sending messages. The same applies to theClient
when it communicates withconnection
/remote ‑ it will send and receive messages on your behalf and forward them to thelistener
you provided. props
function in a companion object of an actor class is usually used as a helper function for constructing an actor. It's needed if your actor takes constructor arguments and you have to take care not to close over mutable state. Remember you can't usenew
operator to create actors, you have to callProps
.- Your
Client
actor will receive messages of typeByteString
as incase data: ByteString =>
once connected to the remote. It will write that data to the TCP connection ‑ effectively sending a message. Whenever it receives a response from remote of typeReceived
as incase Received(data) =>
it will forward it to yourlistener
actor. - See 3.
Client
actor receives messages from yourlistener
and fromconnection
and forwards them accordingly. It does not check however where they came from. So whenever it receivesByteString
it will send it toconnection
/remote, and whenever it receivesReceived
it will send bytes tolistener
. You need to make sure your listener can receive these messages if you want to have 2 way communication.
To summarize here is how 2‑way communication looks like.
Send ByteString
to remote:
MyActor ‑> ByteString
‑> Client ‑> Write(ByteString)
‑> connection/remote
Receive ByteString
from remote (server talks to client):
connection/remote ‑> Received(ByteString)
‑> Client ‑> ByteString
‑> MyActor
where '‑>' is a message send.