简介
- UDP属于全双工类型,可以同时接受和发送信息。因此,下述程序中完成了接受一个信号后发送数据的任务。
代码
s_send = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip_port = ('127.0.0.1', 20225)
s_recv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s_recv.bind(('127.0.0.1', 20225))
while True:
send_buf = bytearray(1024)
print("send**********************************************************")
tlen = 1
send_buf[0:3] = tlen.to_bytes(4, 'little')
cls = "water"
send_buf[4:23] = bytearray(cls, encoding="utf-8")
left = 110
right = 210
top = 310
buttom = 410
sim = 50
send_buf[24:27] = left.to_bytes(4, 'little')
send_buf[28:31] = right.to_bytes(4, 'little')
send_buf[32:35] = top.to_bytes(4, 'little')
send_buf[36:39] = buttom.to_bytes(4, 'little')
send_buf[40:43] = sim.to_bytes(4, 'little')
s_send.sendto(send_buf, ip_port)
print("**********************************************************")
print(" [YOLO Server] Wait for new cmd ...")
data, addr = s_recv.recvfrom(1024)
print(" [YOLO Server] Start to predict ...")
代码解析
- 首先通过 socket.socket 函数创建套接字
- 再通过 .bind() 函数给套接字绑定ip和端口
- 用 bytearray(1024) 设定一个大小为1024字节的值作为传输的值(这个值最大为1024)
- 接着是对传输数据切片赋值
- bytearray(cls, encoding=“utf-8”) 是将字符串类型转化为字节
- .to_bytes(4, ‘little’) 是将整型转化为字节
- .sendto() 函数发送数据
- 但在本程序中采用了 .recvfrom(1024) 函数,会接收 s_recv 传来的数据信号。若没有信号传来,则一直阻塞在这里。