I want to send textual messages over TCP. Pretty easy. I want to do so with akka. I read this article about akka IO: http://doc.akka.io/docs/akka/snapshot/scala/io-tcp.html
Answering your questions:
class Client(remote: InetSocketAddress, listener: ActorRef) extends Actor
takes a listener
which is a reference to an actor that is using this Client
to communicate with remote server. Listener will send and receive messages through this Client
. Since Client
is an actor you will communicate with it solely by sending messages. The same applies to the Client
when it communicates with connection
/remote - it will send and receive messages on your behalf and forward them to the listener
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 use new
operator to create actors, you have to call Props
.Client
actor will receive messages of type ByteString
as in case 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 type Received
as in case Received(data) =>
it will forward it to your listener
actor.Client
actor receives messages from your listener
and from connection
and forwards them accordingly. It does not check however where they came from. So whenever it receives ByteString
it will send it to connection
/remote, and whenever it receives Received
it will send bytes to listener
. 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.