The sockets package allows you to open TCP sockets to servers or to create a TCP server socket yourself.
The following is a very basic example of opening a TCP socket to make an HTTP request and print the first 140 characters of the response.
π¦ sockets π
π π
πΊ ππ π€example.comπ€ 80βοΈ β‘οΈ socket
π¬ socket π π€GET / HTTP/1.1βrβnHost: example.comβrβnβrβnπ€βοΈβοΈ
πΊ π socket 140βοΈ β‘οΈ data
π πΊ π‘ dataβοΈβοΈ
π
At the time of writing this, the above code would return something similar to:
HTTP/1.1 200 OK
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Mon, 10 Sep 2018 08:36:28 GMT
Etag: "15410256
Here weβve an example of a minimal echo-server that listens on port 8728. The server simply sends back a copy of the data it received.
π¦ sockets π
π Simple echo server listening on port 8728
π π
πΊππ 8728βοΈ β‘οΈ server
π π π
πΊ π serverβοΈ β‘οΈ clientSocket
π π π
π data π clientSocket 50βοΈ π
π Weβve read 50 bytes and send them back
π¬ clientSocket dataβοΈ
π
π
ββοΈ error ππ
π
π
π
Of course, the code above is minimal. For example, it can handle only one connection.