Makefile() method of socket class

Overview:

  • The method makefile() of socket class retrieves the file object from a socket and allows reads and writes to the socket using the file I/O semantics.

Example - Server:

# Example Python program that writes to the file object associated with
# a TCP/IP based server socket using the method socket.makefile()
import socket

# Create server socket
svr = socket.socket(socket.AF_INET)

# Bind to an IP & port
svr.bind(("127.0.0.1",1236))

# Enter into listening state
svr.listen()

# Accepting client connections
while(True):
    print("Listening for incoming connections:")

    clientSocket, clientAddress = svr.accept()

    fileObject = clientSocket.makefile("wb", buffering=0)
    fileObject.write("Hello!\n".encode())
    fileObject.write("That was the response from your server...\n".encode())
    print("Sent response to the client")
    fileObject.flush()
    fileObject.close()
    clientSocket.close()

Output:

Listening for incoming connections:

Sent response to the client

Example - Client:

# Example Python program that reads from
# a TCP/IP server socket through the associated file object retrieved # using socket.makefile() method
import socket

# Create a socket and connect to the server
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1",1236))

# Obtain the file object associated with the socket
fileObject = sock.makefile("rbw", buffering=0)

# Read all that the server has sent
while(True):
    data = fileObject.readline()

    if data == b'':
        break

    print(data.decode())
 

Output:

Hello!

 

That was the response from your server...

 


Copyright 2024 © pythontic.com