Python udp协议服务器
时间: 2023-11-19 20:50:01 浏览: 58
Python的UDP协议服务器可以通过以下步骤创建:
```python
import socket
def main():
# 1.创建UDP套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 2.绑定本地地址和端口
local_address = ('', 6666)
udp_socket.bind(local_address)
while True:
# 3.接收对方发送的数据
recv_data = udp_socket.recvfrom(1024)
recv_msg = recv_data[0].decode('utf-8')
recv_address = recv_data[1]
print('当前客户端地址:{},当前接收的信息是:{}'.format(recv_address, recv_msg))
# 可选(发送数据到指定的电脑)
# send_data = input('请输入你要发送的数据:')
# udp_socket.sendto(send_data.encode('utf-8'), ('192.168.2.4', 8080))
# if send_data == 'exit':
# break
# 4.关闭套接字
udp_socket.close()
if __name__ == '__main__':
main()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)