乐闻世界logo
搜索文章和话题

Simple UDP example to send and receive data from same socket

1个答案

1

UDP, or User Datagram Protocol, is a connectionless protocol that enables data transmission between devices on a network. When using UDP for data transmission, it typically involves creating sockets, sending, and receiving data. I will demonstrate using Python as an example to show how to send and receive data from the same socket.

First, you need to install Python and the necessary libraries in your environment. For this example, we only need the socket module from the standard library.

python
import socket def create_udp_socket(): # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return sock def main(): # Create UDP socket sock = create_udp_socket() # Bind to the address and port server_address = ('localhost', 10000) sock.bind(server_address) # Send data message = 'This is a UDP test message' server = ('localhost', 10000) sent = sock.sendto(message.encode(), server) # Receive response on the same socket print('Waiting to receive message') data, address = sock.recvfrom(4096) print(f'Received data: {data.decode()} from {address}') # Close socket sock.close() if __name__ == '__main__': main()

In this simple example, we first create a UDP socket and bind it to the local address and port ('localhost', 10000). Then we send a simple message to the same server address. After sending the message, we use the same socket to receive the response (in real-world scenarios, this is typically a response from the server side). Finally, we close the socket to release resources.

This example assumes that both the server-side and client-side code run on the same host and use the same port number. In practical applications, senders and receivers typically listen and send data on different ports. Additionally, UDP is an unreliable transport protocol, meaning it does not guarantee the order, integrity, or reachability of data packets. Therefore, in applications requiring high reliability, further error handling and acknowledgment mechanisms may be necessary.

2024年8月22日 16:24 回复

你的答案