当前位置: 移动技术网 > IT编程>脚本编程>Python > python实现udp数据报传输的方法

python实现udp数据报传输的方法

2019年03月26日  | 移动技术网IT编程  | 我要评论

郭广昌简历,公务员报考人数,韩国大钟奖

本文实例讲述了python实现udp数据报传输的方法,非常具有实用价值。分享给大家供大家参考。具体方法分析如下:

服务端代码:

import socket 
port = 8081 
s = socket.socket(socket.af_inet,socket.sock_dgram) 
#从给定的端口,从任何发送者,接收udp数据报 
s.bind(("",port)) 
print 'waiting on port:',port 
while true: 
  data,addr = s.recvfrom(1024) 
  #接收一个数据报(最大到1024字节) 
  print 'reciveed:',data,"from",addr 

客户端代码:

import socket 
port = 8081 
host = "localhost" 
s = socket.socket(socket.af_inet,socket.sock_dgram) 
s.sendto("hello world",(host,port)) 

结果:先运行服务端,然后运行客户端,
服务端打印出:

waiting on port: 8081
reciveed: hello world from ('127.0.0.1', 62644)

补充:
socket.sendto(string[, flags], address)

官方文档如下:

send data to the socket. the socket should not be connected to a remote socket, since the destination socket is specified by address. the optional flags argument has the same meaning as for recv() above. return the number of bytes sent. (the format of address depends on the address family — see above.)address参数在协议类型为socket.sock_dgram时,address的结构为一个元组,(host,port)的格式

希望本文所述对大家的python程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网