Open In App

Python – Binding and Listening with Sockets

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 




import socket
import sys
 
 
# specify Host and Port
HOST = ''
PORT = 5789
   
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  
try:
    # With the help of bind() function
    # binding host and port
    soc.bind((HOST, PORT))
      
except socket.error as message:
     
    # if any error occurs then with the
    # help of sys.exit() exit from the program
    print('Bind failed. Error Code : '
          + str(message[0]) + ' Message '
          + message[1])
    sys.exit()
     
# print if Socket binding operation completed   
print('Socket binding operation completed')
  
# With the help of listening () function
# starts listening
soc.listen(9)
  
conn, address = soc.accept()
# print the address of connection
print('Connected with ' + address[0] + ':'
      + str(address[1]))

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:


Article Tags :