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

How to use write/read on UDP socket?

1个答案

1

In traditional UNIX network programming, UDP sockets are typically used with the sendto() and recvfrom() functions rather than write() and read(). This is because UDP is a connectionless protocol, and each UDP datagram (referred to as a datagram) contains destination address information. Therefore, the sendto() and recvfrom() functions allow the program to specify both the destination address and the source address for each message.

However, it is also possible to use the write() and read() functions on UDP sockets, although this approach is less common and has certain limitations. If you decide to use write() and read(), you first need to use the connect() function to establish a connection to a specific remote address and port. This enables you to use write() for sending data and read() for receiving data, just as you would with a connection-oriented TCP socket.

Usage Scenario Example

Suppose we have a client application that needs to send log data to a specific server, and the server's address and port remain constant throughout the session. In this case, we can set up the UDP socket, connect to the server using connect(), and then repeatedly use write() and read() during the session. This simplifies the code because we do not need to specify the server's destination address each time we send data.

Code Example

This is a simple example demonstrating how to set up a UDP socket in Python, use connect(), and perform write and read operations:

python
import socket # Create UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Connect to server's IP and port server_address = ('192.168.1.1', 10000) sock.connect(server_address) try: # Send data message = 'This is a test message' print(f'Sending: {message}') sock.write(message.encode('utf-8')) # Receive response data = sock.read(4096) print(f'Receiving: {data.decode('utf-8')} finally: sock.close()

Conclusion

In practical applications, the choice between write() and read() versus sendto() and recvfrom() depends on the specific application scenario and requirements. If your communication pattern involves a fixed single target or frequently changing targets, this will directly influence your choice. For dynamic targets, using sendto() and recvfrom() is more flexible; however, if the target remains unchanged, using connect() with write() and read() can make the code more concise.

2024年8月23日 18:03 回复

你的答案