- 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
# Create a TCP server socket
serverSocket = socket.socket();
# Bind the tcp socket to an IP and port
# Keep listening
# Keep accepting connections from clients
(clientConnection, clientAddress) = serverSocket.accept();
# Send current server time to the client
serverTimeNow = "%s"%datetime.datetime.now();
print("Sent %s to %s"%(serverTimeNow, clientAddress));
# Close the connection to the client
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 client program in Python that receives the current server time
# IP address of the server
serverIP = "127.0.0.1";
# Port number of the server
serverPort = 40404;
# Create a tcp socket
tcpSocket = socket.socket();
# Connect tcp client socket to the tcp server socket
# 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