Skip to content

Instantly share code, notes, and snippets.

@krestenkrab
Created April 7, 2010 11:48
Show Gist options
  • Save krestenkrab/358787 to your computer and use it in GitHub Desktop.
Save krestenkrab/358787 to your computer and use it in GitHub Desktop.
Eshell V5.7.3 (abort with ^G)
1> {ok,P} = inet_tcp:connect({74,125,79,104},80,[]).
{ok,<port:478>}
2> V1 = inet:send(P, "GET /\n").
ok
3> process_info(self(), messages).
{messages,[{tcp,<port:478>,
"HTTP/1.0 302 Found\r\nLocation: http://www.google.dk/\r\nCache-Control: private\r\nContent-Type: text/html; charset=UTF-8\r\nSet-Cookie: PREF=ID=343fdb84f9eb331b:TM=1270640853:LM=1270640853:S=AaVxF7QpxV4CDNz1; expires=Fri, 06-Apr-2012 11:47:33 GMT; path=/; domain=.google.com\r\nSet-Cookie: NID=33=tEmot8xGMHKZa-gsccbD7tDiXpsHaC24bKm7tSBYgdomt_nceXViDrTzEIn4eosoj7qhYAXVPYr7u60vKjW0UdE-FYN9sP3UmOz89XnvoY8qeVJu5ewjnMgKdmjB7uw8; expires=Thu, 07-Oct-2010 11:47:33 GMT; path=/; domain=.google.com; HttpOnly\r\nDate: Wed, 07 Apr 2010 11:47:33 GMT\r\nServer: gws\r\nContent-Length: 218\r\n\r\n<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n<TITLE>302 Moved</TITLE></HEAD><BODY>\n<H1>302 Moved</H1>\nThe document has moved\n<A HREF=\"http://www.google.dk/\">here</A>.\r\n</BODY></HTML>\r\n"}]}
4>
@krestenkrab
Copy link
Author

While this example does not look like much; there is a lot of stuff happening.

First off, inet_tcp:connect/3 opens the port with the tcp driver, and calls a bunch of setoption's; binds the socket, and then finally does an asynchronous connect. When the driver manager's select-loop determines that the connection can be established; it triggers the driver which then finishes the connect; and sends the {inet_async, ID, ok} back to the caller (which is then receive'd inside inet_tcp:connect/3 which in turn replies {ok,Port}.

The inet:send/2 is equally complicated: it sends the message {command, <pid:shell>, "GET /\n" } to the port, which then tries to write the text "GET /\n" (if that fails it needs to register a select-callback for when writing is possible).

Since the inet port is created in active mode, any incoming data is simply delivered to the owning process as messages at the form {tcp, <port:ID>, Data}; no need to call inet:receive or something like that.

Pretty cool, eh!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment