Free cookie consent management tool by TermsFeed recvfrom() Function Of Python Socket Class | Pythontic.com

Recvfrom() Function Of Python Socket Class

Method Signature:

  socket.recvfrom(bufsize[, flags])

Parameters:

    bufsize - The number of bytes to be read from the UDP socket.

  flags      - This is an optional parameter. As supported by the operating system. Multiple values combined together using bitwise OR. The default                      value is zero.

Return Value:

Returns a bytes object read from an UDP socket and the address of the client socket as a tuple.

Overview:

  • The recvfrom() method of Python's socket class, reads a number of bytes sent from an UDP socket.
  • Like sendto(), the recvfrom()method as well is to be called on a UDP socket.
  • Unlike sendto(), the method recvfrom() does not take an IP address and port as its parameters.
  • The recvfrom() method can be used with an UDP server to receive data from an UDP client or it can be used with an UDP client to receive data from an UDP server.

Example – An UDP server that serves price information:

# ----- An example UDP client in Python that uses recvfrom() method -----

import socket

import random

 

# Give price

def getPrice(corpName):

    if(corpName == "Example Corporation"):

        price = random.uniform(27.0, 29.0)

        return price

    else:

        return "NA"

 

# Create an UDP based server socket

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

socket.bind(("127.0.0.1", 4141))

 

while(True):

    msgAndAddress = socket.recvfrom(1024)

    incName = msgAndAddress[0].decode()

    print(incName)

 

    price = getPrice(incName)

    print(price)

    priceStr = "%.2f"%price 

    socket.sendto(priceStr.encode(), msgAndAddress[1])

Output:

Example Corporation

2019-06-30 01:35:58.801308 28.44

Example Corporation

2019-06-30 01:36:00.150010 28.88

 

Example – An UDP client that asks for price information:

# ----- An example UDP client in Python that uses recvfrom() method -----

import socket

 

# Number of bytes to get

numBytes2Get = 1024

 

# Create a UDP socket. UDP is datagram based.

destination         = ("127.0.0.1", 4141)

udpClientSocket     = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

 

# Send quote request

sentBytesCount      = udpClientSocket.sendto("Example Corporation".encode(), destination)

 

# Use receivefrom() to get quote

receivedBytes  = udpClientSocket.recvfrom(numBytes2Get)

 

# Print the quote

print(receivedBytes[0].decode())

Output:

28.88


Copyright 2025 © pythontic.com