Question

Hi I am a new bee in Erlang but managed to create a simple TCP server which accepts client in passive mode and displays message. I spawn a new process every time new client connects to the server. Is there a way I could send message to the client using the process which gets spawned when client connects.

Here is code.

-module(test).

-export([startserver/0]).

startserver()->
{ok, ListenSocket}=gen_tcp:listen(1235,[binary,{active, false}]),
connect(ListenSocket).

connect(ListenSocket)->
{ok, UserSocket}=gen_tcp:accept(ListenSocket),
Pid=spawn(? MODULE, user,[UserSocket]),
gen_tcp:controlling_process(UserSocket, Pid),
connect(ListenSocket).

user(UserSocket)->
case gen_tcp:recv(UserSocket, 0) of.
{ok, Binary}->% Send basic message.

{error, closed}->% operation on close. 
end.

Can I have some thing like if I do.

Pid!{"Some Message"}. And the message is send to the socket associated with the process with non blocking io,

Was it helpful?

Solution

You could try this tutorial for writing a TCP server using OTP principles: http://learnyousomeerlang.com/buckets-of-sockets#sockserv-revisited

If you use a gen_server instead of your connect loop, you can store the Pids in the state. Then you can use gen_server:cast/2 to send a message to one of the Pids.

The function you want to send a message to the client from the controlling process is gen_tcp:send(Socket, Message), so for example if you wanted to send a one off message on connection you could do this:

user(UserSocket)->
gen_tcp:send(UserSocket, "hello"),
case gen_tcp:recv(UserSocket, 0) of
   {ok, Binary}->% Send basic message.
        gen_tcp:send(UserSocket, "basic message"),
   {error, closed}->% operation on close. 
        gen_tcp:send(UserSocket, "this socket is closing now"),
end.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top