Till now, you must have gained the basic idea about networking and python. If you have missed the last few tutorials, we advice you to go through them, before starting with sockets. Now the real fun begins when we start to mix these things up. So, let's get started with sockets and see what they are and why we use them.
To understand what sockets are, let's start with the Internet Connection. The Internet Connection basically connects two points across the internet for data sharing and other stuff. One process from computer C1 can communicate to a process from computer C2, over an internet connection. It has following properties:
Sockets are the endpoints of a bidirectional, point-to-point communication channel. Given an internet connection, say between client(a browser) and the server(say studytonight.com), we will have two sockets. A
Client Socket and a
Socket acts on two parts: IP Address + Port Number
Vaguely speaking, when you clicked on the link that brought you to Studytonight website, your browser did something like the following:
#a socket object is created for communication clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # now connect to the web server on port 80 # - the normal http port clientsocket.connect(("www.studytonight.com", 80))
This happened on the client side. When the client tries to connect with the server, a random port is assigned by the operating system for the connection. This random port is called Ephermal Port. In the above illustration,
1300 is an ephermal port on the source(client) machine. The client socket is short lived, i.e as soon as the data exchange ends it closes. Now what happens on server is a bit different from client. So,let's see:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #bind the socket to a public host and a well-known port serversocket.bind((socket.gethostname(), 80)) #become a server socket and listen for connections serversocket.listen(5)
For now, just focus on
Connect is used by the client socket to start a connection with the server. This request is fulfilled by bind method of the server socket. If you are having problem with the code, don't worry. Every bit of it will be explained separately with examples.
Before concluding, let's see some differences between the client and the server sockets: