Socketpair() function of socket module in Python

Overview:

  • The socket.socketpair() creates a pair of sockets and connects them together which is returned as a tuple.

  • The communication between the sockets is full-duplex. Both sockets can send and receive simultaneously.

Example:

# Example Python program that creates
# a pair of sockets using socket.socketpair()
# function and uses it for the bidirectional
# communiction between a parent and child process
import socket
import os

def msgParentProc(childSocket):
    childSocket.send("Hi from child".encode())
    print(childSocket.recv(1024).decode())

def msgChildProc(parentSocket):
    parentSocket.send("Hi from parent".encode())
    print(parentSocket.recv(1024).decode())

# Create a socket pair using Unix domain protocol
sockPair = socket.socketpair(socket.AF_UNIX)

childProcSocket     = sockPair[0]
parentProcSocket     = sockPair[1]

retVal    = os.fork()

if retVal == 0:
    print("Child pid:%d"%os.getpid())
    
    #Use child socket
    parentProcSocket.close()
    msgParentProc(childProcSocket)
else:
    print("Parent pid:%d"%os.getpid())
    
    #Use parent socket
    childProcSocket.close()
    msgChildProc(parentProcSocket)

 

Output:

Parent pid:7901

Child pid:7902

Hi from parent

Hi from child

 


Copyright 2024 © pythontic.com