udp协议的socket编程实现
时间: 2023-12-19 09:31:04 浏览: 80
UDP协议的socket编程实现可以分为以下几个步骤:
1. 创建UDP套接字
```python
import socket
# 创建UDP套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
```
2. 绑定端口号
```python
# 绑定端口号
local_addr = ('', 8888)
udp_socket.bind(local_addr)
```
3. 发送数据
```python
# 发送数据
dest_addr = ('192.168.1.100', 8080)
send_data = 'Hello, UDP!'
udp_socket.sendto(send_data.encode('utf-8'), dest_addr)
```
4. 接收数据
```python
# 接收数据
recv_data, src_addr = udp_socket.recvfrom(1024)
print('Received from %s:%s' % src_addr)
print('Received data:', recv_data.decode('utf-8'))
```
完整代码如下:
```python
import socket
# 创建UDP套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定端口号
local_addr = ('', 8888)
udp_socket.bind(local_addr)
# 发送数据
dest_addr = ('192.168.1.100', 8080)
send_data = 'Hello, UDP!'
udp_socket.sendto(send_data.encode('utf-8'), dest_addr)
# 接收数据
recv_data, src_addr = udp_socket.recvfrom(1024)
print('Received from %s:%s' % src_addr)
print('Received data:', recv_data.decode('utf-8'))
# 关闭套接字
udp_socket.close()
```
阅读全文