A small question about TCP Socket of Erlang

Yan Yan yan.beijing.china@REDACTED
Sat Nov 28 19:58:46 CET 2009

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...

In erlang doc, find gen_tcp:connect/3 or 4, we'll find
  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!



More information about the erlang-questions mailing list