Accept Function Of Python Socket Class

Overview:

  • The accept() method of Python's socket class, accepts an incoming connection request from a TCP client.
  • The accept() method is called on a TCP based server socket.
  • When connect() is called at the client side with the IP address and port number of the server, the connect request is received with the  accept() call at the server side.
  • Upon accepting a connection request from a TCP based client, the accept() method called on the server socket returns a socket that is connected to the client.
  • Data can be sent and received using the socket returned by the accept() method.
  • Multithreaded servers spawn a new thread for each of the newly created socket by the accept() method.

 

Example:

# Example server program in Python that serves clients

# with the current server time

 

# import the required Python modules

import socket

import datetime

 

# Create a TCP server socket

serverSocket = socket.socket();

 

# Bind the tcp socket to an IP and port

serverSocket.bind(("127.0.0.1", 40404));

 

# Keep listening

serverSocket.listen();

 

while(True):

    # Keep accepting connections from clients

    (clientConnection, clientAddress) = serverSocket.accept();

 

    # Send current server time to the client

    serverTimeNow = "%s"%datetime.datetime.now();

    clientConnection.send(serverTimeNow.encode());

    print("Sent %s to %s"%(serverTimeNow, clientAddress));

 

    # Close the connection to the client

    clientConnection.close();

 

 

Output:

Sent 2019-06-26 21:38:32.415404 to ('127.0.0.1', 54456)

Sent 2019-06-26 21:38:37.118370 to ('127.0.0.1', 54457)

Sent 2019-06-26 21:38:40.470628 to ('127.0.0.1', 54458)

Sent 2019-06-26 21:38:43.058394 to ('127.0.0.1', 54459)

 

Example:

# Example client program in Python that receives the current server time

import socket

 

# IP address of the server

serverIP    = "127.0.0.1";

 

# Port number of the server

serverPort  = 40404;

 

# Create a tcp socket

tcpSocket   = socket.socket();

 

try:

    # Connect tcp client socket to the tcp server socket

    tcpSocket.connect((serverIP, serverPort));

 

    # Receive data from server (i.e., current server time)

    timeReceived = tcpSocket.recv(1024);

   

    # Print the data received

    print(timeReceived.decode());

except Exception as Ex:

    print("Exception Occurred: %s"%Ex);

 

    # Close the socket upon an exception

    tcpSocket.close();

 

Output:

2019-06-26 21:38:43.058394

 

 


Copyright 2023 © pythontic.com