TCP clarification

Chris Hicks <>
Wed Jun 16 23:33:13 CEST 2010

I'm going to be talking between two Erlang programs through a single port, no distributed Erlang for this project, and wanted to make sure I was thinking about things the right way. First I start listening on the port and spawn a worker process which will accept a connection on that port:
spawn_initial_worker(Port) ->	case gen_tcp:listen(Port, [binary, {reuseaddr, true}, {packet, 0}, {active, false}]) of		{ok, LSock} ->			spawn(?MODULE, worker, [self(), LSock]),			spawn_loop(LSock)	end.
Yes I do want the above to crash if it can't listen. As the only communication gateway into this program if it can't listen there are problems. I then send it into the loop spawn_loop(LSock) which will continually spawn new workers to handle each new incoming connection (may increase to a larger pool of workers later if needed):
spawn_loop(LSock) ->	receive		next_worker ->			spawn_link(?MODULE, worker, [self(), S])	end,	spawn_loop(LSock).
This is the worker process:
worker(Server, LSock) ->	case gen_tcp:accept(LSock) of		{ok, Socket} ->			Server ! next_worker,			%%verify data integrity then spawn process to handle data		{error, Reason} ->			%%some sort of system logging code here to track problems	end.
The way I understand it the Port is basically just an address where programs can thread any number of communications through. Each time gen_tcp:accept(LSock) is called a connection is made between the accepting process and the process on the "other" side trying to connect and send some data on that port. Once they do connect they are in an exclusive two-way communication that will be maintained until the connection is closed. Calling gen_tcp:close(Socket) will close that specific socket (the two-way communication between those two processes) while leaving all other active socket connections unaffected. I would also only need to call gen_tcp:close(Socket) once for any active socket, otherwise if I call it first from the sending process, then call it from the above worker process I would get an {error, Reason} response from the worker process. Is that a generally accurate understanding of how to use ports/sockets?
Hotmail is redefining busy with tools for the New Busy. Get more from your inbox.

More information about the erlang-questions mailing list