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使用Shelve保存对象方法总结

Shelve是一个功能强大的Python模块,用于对象持久性。搁置对象时,必须指定一个用于识别对象值的键。通过这种方式,搁置文件成为存储值的数据库,其中任何一个都可以随时访问。 Pyth...

Django 迁移、操作数据库的方法

文中涉及的示例代码,已同步更新到 HelloGitHub-Team 仓库 我们已经编写了博客数据库模型的代码,但那还只是 Python 代码而已,django 还没有把它翻译成数据库语...

Python 实现Serial 与STM32J进行串口通讯

Python果然是一款非常简明的语言,做东西非常流畅,今天又尝试了一下用Serial做了一个控制台的串口通讯,我用的下位机是STM32F103,搞了一个多小时就成功了,可见Python的...

python2 中 unicode 和 str 之间的转换及与python3 str 的区别

在python2中字符串分为 unicode 和 str 类型   Str To Unicode 使用decode(), 解码   Unicode To Str 使用encode()...

Django logging配置及使用详解

1. settings.py文件 做开发离不开必定离不开日志, 以下是我在工作中写Django项目常用的logging配置. # 日志配置 BASE_LOG_DIR = os.pa...