python_udp数据报传输的实现

来源:互联网 发布:433m模块stc单片机解码 编辑:程序博客网 时间:2024/05/22 06:12

UDP的实现

服务端代码:

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

客户端代码:

import socketport = 8081host = "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 byaddress. The optional flags argument has the same meaning as forrecv() above. Return the number of bytes sent. (The format ofaddress depends on the address family — see above.)address参数在协议类型为socket.SOCK_DGRAM时,address的结构为一个元组,(host,port)的格式


原创粉丝点击