Using TCP
We’ll start our adventures in socket programming by looking at a simple TCP program that fetches data from a server. After this, we’ll write a simple sequential TCP server and show how it can be parallelized to handle multiple parallel sessions.
Fetching Data from a Server
Let’s start by writing a little function called nano_get_url/0
that uses a TCP socket
to fetch an HTML page from http://www.google.com.
socket_examples.erl | |
| nano_get_url() -> |
| nano_get_url("www.google.com"). |
| |
| nano_get_url(Host) -> |
① | {ok,Socket} = gen_tcp:connect(Host,80,[binary, {packet, 0}]), |
② | ok = gen_tcp:send(Socket, "GET / HTTP/1.0\r\n\r\n"), |
| receive_data(Socket, []). |
| |
| receive_data(Socket, SoFar) -> |
| receive |
③ | {tcp,Socket,Bin} -> |
|
Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.