udp实现同时收发信息
import socket
import threading
def fa(udp_socket,recv_ip,recv_data):
# 3 发送信息
while True:
data = input("输入你要发送的数据:")
udp_socket.sendto(data.encode("utf-8"),(recv_ip,recv_data))
def shou(udp_socket):
# 4接收数据
while True:
user_data = udp_socket.recvfrom(1024)
a = user_data[0]
b = user_data[1]
print("用户:%s发来的数据为:%s" % (str(b), a.decode("utf-8")))
def main():
# 1创建套接字
udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# 2 绑定本地信息
udp_socket.bind(("",7892))
recv_ip = input("输入对方ip:")
recv_data = int(input("输入对方端口:"))
t1 = threading.Thread(target=fa,args=(udp_socket,recv_ip,recv_data))
t2 = threading.Thread(target=shou,args=(udp_socket,))
t1.start()
t2.start()
if __name__ == '__main__':
main()
结果:
python做发送udp工具
import socket
from time import sleep
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
nCnt = 0
while True:
if nCnt >5 :
sleep(2)
nCnt = 0
for data in [b'$123;CLEARHOLE;Product_id,Barcode_Cnt,0,NG,05&,\r',
]:
# 发送数据:
s.sendto(data, ('127.0.0.1', 10000))
# 接收数据:CLEARHOLE
#print(s.recv(1024).decode('utf-8'))
sleep(0.5)
nCnt += 1
s.close()
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。