[erlang-questions] A small question about TCP Socket of Erlang
Ngoc Dao
ngocdaothanh@REDACTED
Sun Nov 29 01:02:02 CET 2009
> Why is there a match? SocketOnClient =:= SocketOnServer? Do server and client share the same socket after connection is set?
No. SocketOnServer in step 3 is for matching with SocketOnServer in
step 2. SocketOnServer and SocketOnClient are just values and
independent. To see their values, use io:format("~p~n",
[SocketOnServer]) and io:format("~p~n", [SocketOnClient]).
I think you're confused because of the resemblance of the code for
server and the code for client. But actually this is the beauty of the
design of the API.
On Sun, Nov 29, 2009 at 3:58 AM, Yan Yan <yan.beijing.china@REDACTED> wrote:
> Hi list,
>
> ( It is my first time of socket programming in Erlang, while my former
> experiences were all with Java and C++, so if there is any misunderstanding
> about the concept "socket", it is definitely mine :-) )
>
> For description convenience, I changed some variable's names of
> "socket_examples.erl" on page 245~246 of Joe's book "Programming Erlang".
>
> Here is:
>
> For server,
> step 1: {ok, ListenSocket} = gen_tcp:listen(2345, ...).
> step 2: {ok, SocketOnServer} = gen_tcp:accept(ListenSocket).
> step 3: loop(SocketOnServer) to receive {tcp, SocketOnServer, BinData}.
> step 4: etc...
>
> For client,
> step a: {ok, SocketOnClient} = gen_tcp(Host, 2345, ...).
> step b: gen_tcp:send(SocketOnClient, BinData).
> step c: receive response (as the pattern of {tcp, SocketOnClient, BinData}
> ) from server.
> step d: etc...
>
> plus:
> In erlang doc, find gen_tcp:connect/3 or 4, we'll find
> <Quote>
> Packets can be sent to the returned socket Socket using send/2. Packets
> sent from the peer are delivered as messages:
> {tcp, Socket, Data}
> <End quote>
>
> Then the question is:
> After client's step b, a message as {tcp, SocketOnClient, Data} will be sent
> to server, but the server is in its step 3 looping to receive {tcp,
> SocketOnServer, BinData}.
> Why is there a match? SocketOnClient =:= SocketOnServer? Do server and
> client share the same socket after connection is set?
> ( Similar is why, after server send response message to client, is there a
> match in client's step c... )
>
> I tried to read the source code but failed to get the answer. Shouldn't
> socket be the encapsulation of destination and transmission details only? (
> So sockets in erlang contain details of both ends?)
>
> Thanks for your patience!
>
> Sincerely,
>
> Yan
More information about the erlang-questions
mailing list