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

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

Python模块结构与布局操作方法实例分析

本文实例讲述了Python模块结构与布局操作方法。分享给大家供大家参考,具体如下: #coding=utf8 #起始行 #!/usr/bin/env python #模块文档 '''...

使用WingPro 7 设置Python路径的方法

使用WingPro 7 设置Python路径的方法

Python使用称为Python Path的搜索路径来查找使用import语句导入代码的模块。大多数代码只会汇入已经默认路径上的模块,通过安装到Python的Python标准库的例子模块...

深入Python解释器理解Python中的字节码

深入Python解释器理解Python中的字节码

我最近在参与Python字节码相关的工作,想与大家分享一些这方面的经验。更准确的说,我正在参与2.6到2.7版本的CPython解释器字节码的工作。 Python是一门动态语言,在命令行...

python将处理好的图像保存到指定目录下的方法

原始图像绝对路径的图像名存储在一个txt文件中,下面的程序实现的功能是按照txt文件的顺序,依次将图片读取然后进行处理,最后将处理之后的图像保存在指定的路径下: # Read in...

对Pandas DataFrame缺失值的查找与填充示例讲解

查看DataFrame中每一列是否存在空值: temp = data.isnull().any() #列中是否存在空值 print(type(temp)) print(temp)...