Python – Binding and Listening with Sockets
Last Updated :
01 Jun, 2022
Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server. Note: For more information, refer Socket Programming in Python
Binding and Listening with Sockets
A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port. A server has a listen() method which puts the server into listen mode. This allows the server to listen to incoming connections. And last a server has an accept() and close() method. The accept method initiates a connection with the client and the close method closes the connection with the client.
Example
Python3
import socket
import sys
HOST = ''
PORT = 5789
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try :
soc.bind((HOST, PORT))
except socket.error as message:
print ( 'Bind failed. Error Code : '
+ str (message[ 0 ]) + ' Message '
+ message[ 1 ])
sys.exit()
print ( 'Socket binding operation completed' )
soc.listen( 9 )
conn, address = soc.accept()
print ( 'Connected with ' + address[ 0 ] + ':'
+ str (address[ 1 ]))
|
- First of all we import socket which is necessary.
- Then we made a socket object and reserved a port on our pc.
- After that we bound our server to the specified port. Passing an empty string means that the server can listen to incoming connections from other computers as well. If we would have passed 127.0.0.1 then it would have listened to only those calls made within the local computer.
- After that we put the server into listen mode. 9 here means that 9 connections are kept waiting if the server is busy and if a 10th socket tries to connect then the connection is refused.
Now we need something with which a server can interact. We could tenet to the server like this just to know that our server is working. Type these commands in the terminal:
# start the server
$ python server.py
Keep the above terminal open now open another terminal and type:
$ telnet localhost 12345
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...