SoFunction
Updated on 2024-11-07

Python udp network program to achieve the function of sending and receiving data example

In this article, examples of Python udp network program to achieve the function of sending and receiving data. Shared for your reference, as follows:

1. udp network program - sending data

The process of creating an udp-based network program is simple, and the steps are as follows:

  • Creating client sockets
  • Send/receive data
  • Close Sockets

在这里插入图片描述

The code is as follows:

#coding=utf-8

from socket import *

# 1. create udp sockets
udp_socket = socket(AF_INET, SOCK_DGRAM)

# 2. Preparation of the recipient's address
# '192.168.1.103' indicates the destination ip address
# 8080 indicates the destination port
dest_addr = ('192.168.1.103', 8080) # Note that is a tuple, ip is a string, port is a number

# 3. Getting data from the keyboard
send_data = input("Please enter the data to be sent:")

# 4. send data to a specified program on a specified computer
udp_socket.sendto(send_data.encode('utf-8'), dest_addr)

# 5. Close the socket
udp_socket.close()

Running Phenomena:

Run the script in Ubuntu:

在这里插入图片描述

Run "Network Debugging Assistant" in windows:

在这里插入图片描述

2. udp network program - send, receive data

#coding=utf-8

from socket import *

# 1. create udp sockets
udp_socket = socket(AF_INET, SOCK_DGRAM)

# 2. Preparation of the recipient's address
dest_addr = ('192.168.236.129', 8080)

# 3. Getting data from the keyboard
send_data = input("Please enter the data to be sent:")

# 4. Send data to a designated computer
udp_socket.sendto(send_data.encode('utf-8'), dest_addr)

# 5. waiting to receive data sent by the other party
recv_data = udp_socket.recvfrom(1024) # 1024 indicates the maximum number of bytes for this reception

# 6. display the data sent by the other party
# The received data recv_data is a tuple
# The first element is the data sent by the other party
# The 2nd element is the other side's ip and port
print(recv_data[0].decode('gbk'))
print(recv_data[1])

# 7. closing sockets
udp_socket.close()

python script:

在这里插入图片描述

Network Debugging Assistant screenshot:

在这里插入图片描述

More about Python related content can be viewed on this site's topic: thePython Socket Programming Tips Summary》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques

I hope that what I have said in this article will help you in Python programming.