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程序设计有所帮助。

相关文章

Django添加KindEditor富文本编辑器的使用

KindEditor简介: KindEditor是一套开源的在线HTML编辑器,主要用于让用户在网站上获得所见即所得编辑效果,开发人员可以用KindEditor 把传统的多行文本输入框...

python3 写一个WAV音频文件播放器的代码

环境:ubuntu 16.04 python3.5 pycharm 包 : wave pyaudio sys 上代码:AudioPlayer.py # coding:utf-8 #...

Python实现Smtplib发送带有各种附件的邮件实例

Python实现Smtplib发送带有各种附件的邮件实例

这两天对Python的邮件模块比较感兴趣,于是就查了查资料。同时在实际的编码过程中也遇到了各种各样的问题。下面我就来分享一下我与smtplib的故事。 前提条件 我的上一篇博文里面讲解了...

Python上下文管理器类和上下文管理器装饰器contextmanager用法实例分析

本文实例讲述了Python上下文管理器类和上下文管理器装饰器contextmanager用法。分享给大家供大家参考,具体如下: 一. 什么是上下文管理器 上下文管理器是在Python2....

Python使用pymongo库操作MongoDB数据库的方法实例

python操作mongodb数据库 # !/usr/bin/env python # -*- coding:utf-8 -*- """ 使用pymongo库操作MongoDB数据库...