Recv Function Of Python Socket Class

Method Signature/Syntax:

  recv(bufsize[, flags])

Parameters:

    bufsize - No of bytes to receive.

flags - Supports values as specified the operating system. Multiple flags can be combined by doing a bitwise OR.

             

Return Value:

    Returns the received data as bytes object.

             

Overview: 

  • Unlike send(), the recv() function of Python's socket module can be used to receive data from both TCP and UDP sockets.
  • The example client and server programs given here for UDP, use recv() at both client and the server sides.

Example – UDP Server:

# ----- Example UDP based server program in Python that uses recv() function -----

 

import socket

 

# Define IP address and port number

ipAddress       = "127.0.0.1";

portNumber      = 3131;

 

# Create a UDP socket

udpSvr = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);

 

# Bind the UDP socket to the IP address and the port number

udpSvr.bind((ipAddress, portNumber))

 

# Receive datagrams from clients forever

bufferSize = 1024;

 

# Receive incoming datagrams

while(True):

    udpClientData = udpSvr.recvfrom(bufferSize);

 

    # Datagram from client

    datagramFromClient      = udpClientData[0];

 

    # Datagram from server

    datagramSourceAddress   = udpClientData[1] ;  

   

    print(udpClientData);

    udpSvr.sendto("Datagram from Server".encode(), datagramSourceAddress);

Output:

(b'Datagram from Client', ('127.0.0.1', 50559))

(b'Datagram from Client', ('127.0.0.1', 57225))

Example – UDP Client:

# ----- Example UDP client program in Python that uses recv() function -----

import socket

 

msg         = "Datagram from client";

ipAndPort   = ("127.0.0.1", 3131);

udpClient   = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);

 

# Send a datagram to the UDP server

udpClient.sendto(msg.encode(), ipAndPort);

 

# Receive a reply from UDP server

datagramFromServer  = udpClient.recv(1024);

 

# Print the received datagram from server

print(datagramFromServer.decode());

Output:

Datagram from Server

 


Copyright 2023 © pythontic.com