Why use “socket”?
Sockets are backbone of networking. They make the transfer of information possible between two or more applications or devices.
What is a “socket”?
A socket is one endpoint of a two-way communication link between two system running on the network.
A socket is bound to a port number so that the connection layer can identify which application the data is destined to be sent to.
An endpoint is a combination of an IP address and a port number.
Additional reading: https://en.wikipedia.org/wiki/IP_address
A protocol is a standard set of rules for transferring data
|Protocol||Port Number||Python Library||Function|
|HTTP||80||httplib, urllib||Web Pages|
|FTP||21||ftplib, urllib||File Transfer|
**Just a few samples, there are a lot more. We will concentrate on HTTP and urllib library first.
Additional reading: https://docs.python.org/3/library/http.html
Additional reading: https://docs.python.org/3/library/ftplib.html
Additional reading: https://docs.python.org/3/library/poplib.html
Additional reading: https://docs.python.org/3/library/telnetlib.html
Additional reading: https://docs.python.org/3/library/smtplib.html
Can we use Python instead of a browser?
Yes, we can use Python and urllib or httplib library. You can read the example below
Additional reading: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
Below is a sample conversation between an HTTP client and an HTTP server running on www.example.com, port 80.
GET / HTTP/1.1 Host: www.example.com
HTTP/1.1 200 OK Date: Mon, 23 May 2005 22:38:34 GMT Content-Type: text/html; charset=UTF-8 Content-Length: 155 Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT Server: Apache/18.104.22.168 (Unix) (Red-Hat/Linux) ETag: "3f80f-1b6-3e1cb03b" Accept-Ranges: bytes Connection: close <html> <head> <title>An Example Page</title> </head> <body> <p>Hello World, this is a very simple HTML document.</p> </body> </html>
We will do or try to use a lower level approach on our next session, for now let's use the easiest way.
What is “urllib” library?
It’s a URL handling module for Python.
It is used to fetch (Uniform Resource Locators). It uses the “urlopen” function to fetch its content.
Additional reading: https://en.wikipedia.org/wiki/URL
Additional reading: https://docs.python.org/3/library/urllib.html
The code below will read the page or web content from python.org web site.
from urllib import request
r = request.urlopen(“http://python.org”)
Additional reading: https://docs.python.org/3/library/urllib.request.html#module-urllib.request
The code below will download a file from the given website.
from urllib import request
url = “http://ftp.lysator.liu.se/pub/awe32/soundfonts/mean.zip”
r = request.urlopen(url)
f = open(“mean.zip”, “wb”)
All source codes are available here
You can freely download and copy them.
Video channel coming soon!