Reputation: 785
I have just started off on Erlang. I want to create a TCP server in Erlang. My TCP client runs on Android and connects to the server. I have taken the TCP server implementation from https://github.com/kevinlynx/erlang-tcpserver
I am able to run the server, connect the client to it and send messages from the client to the server. Also, the logic in the server is that whenever it receives a messages from the client, it sends back the same message to the client.
All this works fine, my only problem is how do I send a message to client from the erlang shell(without having to wait for a message from client). The gen_tcp:send() function requires as input the Socket handle, whenever client sends a message, there is a callback and it has the socket handle so it can be used to send message back to the client, but how to do it otherwise?
Upvotes: 1
Views: 826
Reputation: 48589
I have just started off on Erlang. I want to create a TCP server in Erlang.
I think the problem is that you are using software that sets up a communication channel between a client and a sever:
(client) ================== (server)
Now you have a third entity:
(client) ================== (server)
(erlang shell)
and you want the erlang shell to communicate with the client. That's all well and good, but the code you are using doesn't provide for that. It sounds like you also want your client to act as a server for the erlang shell. Why do you need the erlang shell to send messages to the client?
The erlang shell could become a second client of the server:
(client) ================== (server)
(erlang shell) ============ (server)
but that doesn't help the erlang shell communicate directly with the client. The erlang shell could send some information to the sever, and the server could store that information in the State, then the server could pass the State to the client the next time the client made a request.
If the erlang shell had the Pid of the client, the erlang shell could always do:
Pid ! "hello client"
and if the client were waiting in a receive-statement, then the client could extract that message from its mailbox. What does your client look like?
Upvotes: 0
Reputation: 1189
On the server side, you must be accepting the connection somewhere:
{ok, Sock} = gen_tcp:accept(LSock)
And I suppose you could send a message to that socket:
gen_tcp:send(Sock, YourPacket)
If you do not accept connections then it is not a server.
Updating to answer comment
One way is sharing the listener socket (LSock
in the example). You could save it on an accessible ETS and call the acceptor from the shell despite it not been the owner of the listener.
Otherwise you are going to have to wrap everything on a server where you keep the opened socket/s in a State
, and program a handle to send messages to opened sockets. A nice explanation of a socket server can be found here.
Upvotes: 3