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

yipeiwu_com6年前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中datetime模块中strftime/strptime函数的使用

python中datetime模块中strftime/strptime函数的使用

Python 的datetime模块 其实就是date和time 模块的结合,常见的属性方法都比较常用 比如: datetime.day,datetime.month,datet...

Django重装mysql后启动报错:No module named ‘MySQLdb’的解决方法

Django重装mysql后启动报错:No module named ‘MySQLdb’的解决方法

发现问题 最近由于卸载Mysql时将很多相关依赖包都卸载了,重装mysql后启动django出现如下错误: django.core.exceptions.ImproperlyConf...

Python实现抢购IPhone手机

要买IPhone7主要有三个途径吧,一是官网下单;二是官网预约,直营店取货;三是第三方渠道。第一个渠道需要等3-4周,而且是直接快递过来,方便是方便,缺点主要是对物流不放心和怕遇到瑕疵机...

Django 响应数据response的返回源码详解

响应数据的返回 在 WSGIHandler.__call__(self, environ, start_response) 方法调用了 WSGIHandler.get_response...

python中getattr函数使用方法 getattr实现工厂模式

看了下函数本身的doc复制代码 代码如下:getattr(object, name[, default]) -> value Get a named attribute from...