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

相关文章

python3实现小球转动抽奖小游戏

python3实现小球转动抽奖小游戏

最近老师在讲 tkinter,所以我做了一个抽奖小游戏。 一、效果图 先上效果图。红色的小球会围绕蓝色小球做环形运动。我设置的四个角是奖品,其余的都是再接再厉。 二、方法 基于tkin...

Python读取实时数据流示例

1、#coding:utf-8 chose = [ ('foo',1,2), ('bar','hello'), ('foo',3,4) ] def do_foo(x,y...

Python 实现训练集、测试集随机划分

Python 实现训练集、测试集随机划分

随机从列表中取出元素: import random dataSet = [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]...

Python实现模拟分割大文件及多线程处理的方法

本文实例讲述了Python实现模拟分割大文件及多线程处理的方法。分享给大家供大家参考,具体如下: #!/usr/bin/env python #--*-- coding:utf-8...

Python for循环中的陷阱详解

Python for循环中的陷阱详解

前言 Python 中的 for 循环和其他语言中的 for 循环工作方式是不一样的,今天就带你深入了解 Python 的 for 循环,看看它是如何工作的,以及它为什么按照这种方式工作...