一段发包代码,在python2.x下没问题:
udp_sock_fd.sendto(msg, (target_ip, target_port))
但在python3.x下出现错误,提示:
TypeError: a bytes-like object is required, not 'str'
python3.x和python2.x对于参数类型定义不同,
python3.x使用bytes, python2使用str类型,
bytes和str可以通过encode(), decode()相互转换,
str--->bytes:encode(),将str转换为bytes。
bytes--->str:decode(),把bytes变为str。
python3.x这么写就对了:
udp_sock_fd.sendto(msg.encode(), (target_ip, target_port))