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
The article present a simple implementation of a TCP client, but it's not clear to me how I would use this client.
The constructor takes an InetSocketAddress and an ActorRef. InetSocketAddress make sense (I assume this is the of the destination) but what's the ActorRef? this is my first time using akka, but from what I understand, ActorRef is the reference of another actor. Since my TCP client is an actor, and I expect this TCP actor to communicate with a TCP server, not with another actor, why would I give it an actor ref?
what's the props function in the companion object for?
once instantiated, how would I use this actor to send TCP messages? Should I just send it a message with the data I want to send in the form of a ByteString?
4. what's the connection / difference between
case Received(data) =>
listener ! data
and
case data: ByteString =>
connection ! Write(data)
Answering your questions:
class Client(remote: InetSocketAddress, listener: ActorRef) extends Actortakes alistenerwhich is a reference to an actor that is using thisClientto communicate with remote server. Listener will send and receive messages through thisClient. SinceClientis an actor you will communicate with it solely by sending messages. The same applies to theClientwhen it communicates withconnection/remote - it will send and receive messages on your behalf and forward them to thelisteneryou provided.propsfunction 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 usenewoperator to create actors, you have to callProps.Clientactor will receive messages of typeByteStringas 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 typeReceivedas incase Received(data) =>it will forward it to yourlisteneractor.Clientactor receives messages from yourlistenerand fromconnectionand forwards them accordingly. It does not check however where they came from. So whenever it receivesByteStringit will send it toconnection/remote, and whenever it receivesReceivedit 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
ByteStringto remote:MyActor ->
ByteString-> Client ->Write(ByteString)-> connection/remoteReceive
ByteStringfrom remote (server talks to client):connection/remote ->
Received(ByteString)-> Client ->ByteString-> MyActorwhere '->' is a message send.