将多任务(多线程)引入到udp聊天机器人,可以实现同时发送消息和接收消息
1 import socket
2 import threading
3
4
5 def udp_send(udp_socket,ip,port):
6 while true:
7 try:
8 # 获取发送的信息
9 data = input('请输入要发送的信息:')
10 udp_socket.sendto(data.encode('gbk'), (ip,port))
11
12 except exception as erro:
13 print('错误类型:',erro)
14
15
16 def udp_recv(udp_socket):
17 while true:
18 # 接收信息
19 recv_data = udp_socket.recvfrom(1024)
20 print('接收的信息:',recv_data[0].decode('gbk'))
21
22
23 def main():
24
25 # 创建udp套接字
26 udp_socket = socket.socket(socket.af_inet, socket.sock_dgram)
27
28 # 绑定本地信息
29 udp_socket.bind(('',8080))
30
31 # 获取对方通信地址