Listen() Function Of Socket Class In Python

Overview:

  • Calling listen() makes a socket ready for accepting connections.
  • The listen() method should be called before calling the accept() method on the server socket.
  • The listen() function accepts a queue size through the parameter backlog. This denotes maximum number of connections that can be queued for this socket by the operating system. Once 'backlog' number of connections is in the socket's queue, the kernel will reject incoming connections to the socket.

Example – Quote of the day Server:

# ----- A Python program implementing a Quote of the Day server -----

import socket

import datetime

from random import randint

 

quotes = [ ("The secret of education lies in respecting the pupil", "Ralph Waldo Emerson"),

           ("Know thyself", "Socrates"),

           ("For knowledge itself is Power", "Francis Bacon"),

           ("Nothing is worth more than this day", "Goethe"),

           ("Ah! happy years! once more who would not be a boy","Byron: Child Harold")];

 

qotdPortNumber      = 32017;

qotdServerSocket    = socket.socket();

 

qotdServerSocket.bind(("127.0.0.1", qotdPortNumber));

qotdServerSocket.listen();

print("Quote of the day requests welcome:");

 

while(True):

    (socketForClient, clientIP) = qotdServerSocket.accept();

   

    # Pick a random quote

    quoteIndex      = randint(0, 4);

    quoteOfTheDay   = "%s - %s"%(quotes[quoteIndex][0],quotes[quoteIndex][1]);

    encodedMsg      = quoteOfTheDay.encode();

 

    socketForClient.send(encodedMsg);

    timeVal = datetime.datetime.now();

    print("%s Just served: %s, to client with IP address and port: %s"%(timeVal, quoteOfTheDay, clientIP));

    socketForClient.close();

Output:

Quote of the day requests welcome:

2019-06-26 15:30:10.179610 Just served: Ah! happy years! once more who would not be a boy - Byron: Child Harold, to client with IP address and port: ('127.0.0.1', 51243)

2019-06-26 15:30:23.094655 Just served: The secret of education lies in respecting the pupil - Ralph Waldo Emerson, to client with IP address and port: ('127.0.0.1', 51244)

 

Example – Quote of the day Client:

# ----- Example Python program to connect to a Quote of the Day server -----

import socket

 

# Server IP address and Port

qotdServerIP    = "127.0.0.1";

qotdServerPort  = 32017;

 

# Create client socket instance

qotdClient =  socket.socket();

 

# Connect to the quote of the day server

# No need to send any message to server

# Server replies with a quote upon receiving a client connection

qotdClient.connect((qotdServerIP, qotdServerPort));

 

# Get the reply

quoteOfTheDay = qotdClient.recv(1024);

 

# Print the reply

print("Quote of the day:%s"%quoteOfTheDay.decode());

 

 

Output:

Quote of the day:The secret of education lies in respecting the pupil - Ralph Waldo Emerson

 


Copyright 2019 © pythontic.com