|
|
| Author |
Message |
< Erlang ~ learning - help correct this code |
| himadripalit |
Posted: Fri Apr 24, 2009 11:45 am |
|
|
|
Joined: 24 Apr 2009
Posts: 1
|
Hello All,
Can someone please tell me why cant I do something like this, I am totally new to erlang , this the stupid looking code:
Code: -module(clientserver).
-export([client/1]).
client(N) ->
register(client,spawn(fun() -> receive_ans() end)),
server ! {double_of,N}.
receive_ans() ->
server(),
receive
{answer,Result} -> {Result}
end.
server() ->
register(server,spawn(fun() -> loop() end)).
loop() ->
receive
{double_of,X} ->
client ! {answer,X*2},
loop()
end.
after I compile I get
c(clientserver).
./clientserver.erl:14: Warning: function server/0 is unused
./clientserver.erl:18: Warning: function loop/0 is unused
{ok,clientserver}
and needless to say,I get an error on running as server/0 and loop/0 not getting recognised.
Update: I realised that server/0 wasnt getting called so put a call to server/0 in receive_ans(). Now it compiles but an error occurs on calling
Code: clientserver:client(7).
** exception error: bad argument
in function clientserver:client/1
Thanks to keymone pointing it out, calling server() from receive_ans wasnt the right thing to do as this means creating a server process every time a client sends a request to the server.
Also he sent me the correct code, so here it is :
Code: -module(clientser).
-compile(export_all).
client(N) ->
ClientPID = self(),
aserver ! {ClientPID, double_of, N},
receive {answer, R} -> R end.
server() ->
register(aserver, spawn(fun() -> loop() end)).
loop() ->
receive
{ClientPID, double_of, N} ->
ClientPID ! {answer, N*2},
loop()
end.
Before running it, the server needs to be started and voila!
Thanks keymone. |
Last edited by himadripalit on Fri Apr 24, 2009 1:38 pm; edited 2 times in total |
|
| Back to top |
|
| keymone |
Posted: Fri Apr 24, 2009 12:30 pm |
|
|
|
User
Joined: 17 Sep 2007
Posts: 11
Location: Lviv, Ukraine
|
|
| Back to top |
|
|
|
All times are GMT
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You cannot download files in this forum
|
|
|