Accept Function Of Python Socket Class


  • 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 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(("", 40404));


# Keep listening




    # Keep accepting connections from clients

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


    # Send current server time to the client

    serverTimeNow = "%s";


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


    # Close the connection to the client





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

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

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

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



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

import socket


# IP address of the server

serverIP    = "";


# Port number of the server

serverPort  = 40404;


# Create a tcp socket

tcpSocket   = socket.socket();



    # 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


except Exception as Ex:

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


    # Close the socket upon an exception




2019-06-26 21:38:43.058394



Copyright 2019 ©