Reputation: 136
I've learned how to write a python server, and figured out that I have a hole in my knowledge.
Therefore, I would glad to know more about the differences between the commands bind()
, listen()
of the module called socket.
In addition, when I use bind()
with a specific port as a parameter, Is the particular port being in use already, before using the listen()
method?!
Upvotes: 7
Views: 12981
Reputation: 346
I found a tutorial which explains in detail:
... bind() is used to associate the socket with the server address.
Calling listen() puts the socket into server mode, and accept() waits for an incoming connection.
listen()
is what differentiates a server socket from a client.
Once bind()
is called, the port is now reserved and cannot be used again until either the program ends or the close()
method is called on the socket.
A test program that demonstrates this is as follows:
import socket
import time
HOST = '127.0.0.1'
PORT = 65432
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
while 1:
time.sleep(1)
when running two instances of this program at once, you can see that the one started last has the error:
Which proves that the port is reserved before listen()
is ever called.
Upvotes: 10