python实现的udp协议Server和Client代码实例

yipeiwu_com5年前Python基础
直接上代码:
Server端:
复制代码 代码如下:

 #!/usr/bin/env python
 # UDP Echo Server -  udpserver.py
 import socket, traceback

 host = ''
 port = 54321

 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 s.bind((host, port))

 while 1:
     try:
         message, address = s.recvfrom(8192)
         print "Got data from", address, ": ", message
         s.sendto(message, address)
     except (KeyboardInterrupt, SystemExit):
         raise
     except:
         traceback.print_exc()
 

Client端:
复制代码 代码如下:
1 #!/usr/bin/env python
 # UDP Client - udpclient.py
 import socket, sys

 host = sys.argv[1]
 textport = sys.argv[2]

 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 try:
     port = int(textport)
 except ValueError:
     port = socket.getservbyname(textport, 'udp')
 s.connect((host, port))
 while 1:
     print "Enter data to transmit:"
     data = sys.stdin.readline().strip()
     s.sendall(data)
     print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
     buf = s.recv(2048)
     if not len(buf):
         break
     print "Server replies: ",
     sys.stdout.write(buf)
     print "\n"
 

相关文章

python内置函数sorted()用法深入分析

本文实例讲述了python内置函数sorted()用法。分享给大家供大家参考,具体如下: 列表对象提供了sort()方法支持原地排序,而内置函数sorted()不支持原地操作只是返回新的...

Python生成词云的实现代码

Python生成词云的实现代码

1 概述 利用Python生成简单的词云,需要的工具是cython,wordcloud与anaconda. 2 准备工作 包括安装cython,wordcloud与anaconda. 2...

python构建指数平滑预测模型示例

python构建指数平滑预测模型示例

指数平滑法 其实我想说自己百度的… 只有懂的人才会找到这篇文章… 不懂的人…看了我的文章…还是不懂哈哈哈 指数平滑法相比于移动平均法,它是一种特殊的加权平均方法。简单移动平均法用的是算术...

Python判断变量是否已经定义的方法

Python判断变量是否已经定义是一个非常重要的功能,本文就来简述这一功能的实现方法。 其实Python中有很多方法可以实现判断一个变量是否已经定义了。这里就举出最常用的两种作为示例,如...

python生成二维码的实例详解

python生成二维码的实例详解 版本相关 操作系统:Mac OS X EI Caption Python版本:2.7 IDE:Sublime Text 3 依赖库 Pyth...