Python自动化之socketserver模块
1 动态导入模块
import importlib
aa = importlib.import_module("lib1.aa") //lib跟当前模块不是一个目录,aa是lib下的一个模块
print(aa)
print(aa.C.age)
2 socket介绍
Socket Families(地址簇)
socket.AF_UNIX unix本机进程间通信
socket.AF_INET IPV4
socket.AF_INET6 IPV6
These constants represent the address (and protocol) families, used for the first argument to socket(). If the AF_UNIX constant is not defined then this protocol is unsupported. More constants may be available depending on the system.
Socket Types
socket.SOCK_STREAM #for tcp
socket.SOCK_DGRAM #for udp
socket.SOCK_RAW
原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以;其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。
socket.SOCK_RDM
是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问,在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。
socket.SOCK_SEQPACKET 废弃了
These constants represent the socket types, used for the second argument to socket(). More constants may be available depending on the system. (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.)
socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None) 必会
Create a new socket using the given address family, socket type and protocol number. The address family should be AF_INET (the default), AF_INET6, AF_UNIX, AF_CAN or AF_RDS. The socket type should beSOCK_STREAM (the default), SOCK_DGRAM, SOCK_RAW or perhaps one of the other SOCK_ constants. The protocol number is usually zero and may be omitted or in the case where the address family is AF_CAN the protocol should be one of CAN_RAW or CAN_BCM. If fileno is specified, the other arguments are ignored, causing the socket with the specified file descriptor to return. Unlike socket.fromfd(), fileno will return the same socket and not a duplicate. This may help close a detached socket using socket.close().
socket.socketpair([family[, type[, proto]]])
Build a pair of connected socket objects using the given address family, socket type, and protocol number. Address family, socket type, and protocol number are as for the socket() function above. The default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
socket.create_connection(address[, timeout[, source_address]])
Connect to a TCP service listening on the Internet address (a 2-tuple (host, port)), and return the socket object. This is a higher-level function than socket.connect(): if host is a non-numeric hostname, it will try to resolve it for both AF_INET and AF_INET6, and then try to connect to all possible addresses in turn until a connection succeeds. This makes it easy to write clients that are compatible to both IPv4 and IPv6.
Passing the optional timeout parameter will set the timeout on the socket instance before attempting to connect. If no timeout is supplied, the global default timeout setting returned by getdefaulttimeout() is used.
If supplied, source_address must be a 2-tuple (host, port) for the socket to bind to as its source address before connecting. If host or port are ‘’ or 0 respectively the OS default behavior will be used.
socket.getaddrinfo(host, port, family=0, type=0, proto=0, flags=0)
获取要连接的对端主机地址 必会
sk.bind(address) 必会
s.bind(address) 将套接字绑定到地址。address地址的格式取决于地址族。在AF_INET下,以元组(host,port)的形式表示地址。
sk.listen(backlog) 必会
开始监听传入连接。backlog指定在拒绝连接之前,可以挂起的最大连接数量。
backlog等于5,表示内核已经接到了连接请求,但服务器还没有调用accept进行处理的连接个数最大为5
这个值不能无限大,因为要在内核中维护连接队列
sk.setblocking(bool) 必会
是否阻塞(默认True),如果设置False,那么accept和recv时一旦无数据,则报错。
sk.accept() 必会
接受连接并返回(conn,address),其中conn是新的套接字对象,可以用来接收和发送数据。address是连接客户端的地址。
接收TCP 客户的连接(阻塞式)等待连接的到来
sk.connect(address) 必会
连接到address处的套接字。一般,address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。
sk.connect_ex(address)
同上,只不过会有返回值,连接成功时返回 0 ,连接失败时候返回编码,例如:10061
sk.close() 必会
关闭套接字
sk.recv(bufsize[,flag]) 必会
接受套接字的数据。数据以字符串形式返回,bufsize指定最多可以接收的数量。flag提供有关消息的其他信息,通常可以忽略。
sk.recvfrom(bufsize[.flag])
与recv()类似,但返回值是(data,address)。其中data是包含接收数据的字符串,address是发送数据的套接字地址。
sk.send(string[,flag]) 必会
将string中的数据发送到连接的套接字。返回值是要发送的字节数量,该数量可能小于string的字节大小。即:可能未将指定内容全部发送。
sk.sendall(string[,flag]) 必会
将string中的数据发送到连接的套接字,但在返回之前会尝试发送所有数据。成功返回None,失败则抛出异常。
内部通过递归调用send,将所有内容发送出去。
sk.sendto(string[,flag],address)
将数据发送到套接字,address是形式为(ipaddr,port)的元组,指定远程地址。返回值是发送的字节数。该函数主要用于UDP协议。
sk.settimeout(timeout) 必会
设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如 client 连接最多等待5s )
sk.getpeername() 必会
返回连接套接字的远程地址。返回值通常是元组(ipaddr,port)。
sk.getsockname()
返回套接字自己的地址。通常是一个元组(ipaddr,port)
sk.fileno()
套接字的文件描述符
socket.sendfile(file, offset=0, count=None)
发送文件 ,但目前多数情况下并无什么卵用。
3 socketserver介绍

import socket
server = socket.socket() #获得socket实例
server.bind(("localhost",9998)) #绑定ip port
server.listen() #开始监听
print("等待客户端的连接...")
conn,addr = server.accept() #接受并建立与客户端的连接,程序在此处开始阻塞,只到有客户端连接进来...
print("新连接:",addr )
while True:
data = conn.recv(1024)
print("收到消息:",data)
conn.send(data.upper())
server.close()
socketserver 支持多次交互
import socket
client = socket.socket()
client.connect(("localhost",9998))
while True:
msg = input(">>:").strip()
if len(msg) == 0:continue
client.send( msg.encode("utf-8") )
data = client.recv(1024)
print("来自服务器:",data)
client.close()
socket客户端支持多交互
实现了多次交互, 棒棒的, 但你会发现一个小问题, 就是客户端一断开,服务器端就进入了死循环,为啥呢?
看客户端断开时服务器端的输出
等待客户端的连接...
新连接: ('127.0.0.1', 62722)
收到消息: b'hey'
收到消息: b'you'
收到消息: b'' #客户端一断开,服务器端就收不到数据了,但是不会报错,就进入了死循环模式。。
收到消息: b''
收到消息: b''
收到消息: b''
收到消息: b''
知道了原因就好解决了,只需要加个判断服务器接到的数据是否为空就好了,为空就代表断了。。。
import socket
server = socket.socket() #获得socket实例
server.bind(("localhost",9998)) #绑定ip port
server.listen() #开始监听
print("等待客户端的连接...")
conn,addr = server.accept() #接受并建立与客户端的连接,程序在此处开始阻塞,只到有客户端连接进来...
print("新连接:",addr )
while True:
data = conn.recv(1024)
if not data:
print("客户端断开了...")
break
print("收到消息:",data)
conn.send(data.upper())
server.close()
加了判断客户端是否断开的代码
4 socketserver实例
__author__ = "wushipeng"
import socketserver
class MyTcpHandle(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
self.data = self.request.recv(1024).strip()
print("%s wrote data" % self.client_address[0])
print(self.data)
self.request.send(self.data.upper())
except ConnectionResetError as e:
print("err",e)
break
if __name__ == "__main__":
server = socketserver.TCPServer(("localhost",9999),MyTcpHandle)
server.serve_forever()
Python自动化之socketserver模块的更多相关文章
- python网络编程socketserver模块(实现TCP客户端/服务器)
摘录python核心编程 socketserver(python3.x版本重新命名)是标准库中的网络编程的高级模块.通过将创建网络客户端和服务器所必须的代码封装起来,简化了模板,为你提供了各种各样的类 ...
- Python自动化之常用模块
1 time和datetime模块 #_*_coding:utf-8_*_ __author__ = 'Alex Li' import time # print(time.clock()) #返回处理 ...
- Python自动化开发 - select模块
介绍: IO-多路复用:监听多个socker对象是否有变化,包括可读.可写.发送错误 Python中的select模块专注于I/O多路复用,提供了select poll epoll三个方法(其中后两个 ...
- Python自动化开发 - 常用模块(二)
本节内容 1.shutil模块 2.shelve模块 3.xml处理模块 4.configparser模块 5.hashlib模块 6.subprocess模块 7.re模块 一.shutil模块 高 ...
- python网络编程-socketserver模块
使用socketserver 老规矩,先引入import socketserver 必须创建一个类,且继承socketserver.BaseRequestHandler 这个类中必须重写handle( ...
- python学习之-- socketserver模块
socketserver 模块简化了网络服务器的编写,主要实现并发的处理. 主要有4个类:这4个类是同步进行处理的,另外通过ForkingMixIn和ThreadingMixIn类来支持异步.sock ...
- Python 深入剖析SocketServer模块(二)(V2.7.11)
五.Mix-In混合类 昨天介绍了BaseServer和BaseRequestHandler两个基类,它们只用与派生,所以贴了它们派生的子类代码. 今天介绍两个混合类,ForkingMix-In 和 ...
- Python自动化开发 - 常用模块(一)
本节内容 1.模块介绍 2.time&datetime模块 3.random模块 4.os模块 5.sys模块 6.json&pickle模块 7.logging模块 一.模块介绍 模 ...
- Python自动化之logging模块
Logging模块构成 主要分为四个部分: Loggers:提供应用程序直接使用的接口 Handlers:将Loggers产生的日志传到指定位置 Filters:对输出日志进行过滤 Formatter ...
随机推荐
- Spring MVC启动过程
org.springframework.web.context.ContextLoaderListener ContextLoaderListener的作用就是启动Web容器时,自动装配Applica ...
- VIP卡
VIP卡:http://item.taobao.com/item.htm?id=6826715667&ali_refid=a3_420435_1006:1102617497:6::683ff3 ...
- eclipse-4.4.2安装Groovy插件(其他版本eclipse可参考)
步骤 : 1.启动eclipse,点击help -> Install New Software... 在弹出的窗口中点击:Add... Groovy插件的地址:http://dist.sprin ...
- UCMA设置lync在线状态
摘要 UCMA全称Microsoft Unified Communications Managed API,主要用来构建工作在Microsoft Lync Server上的中间层应用程序.开发人员可以 ...
- PPTP(Point to Point Tunneling Protocol),即点对点隧道协议。
PPTP PPTP(Point to Point Tunneling Protocol),即点对点隧道协议.该协议是在PPP协议的基础上开发的一种新的增强型安全协议,支持多协议虚拟专用网(VPN),可 ...
- 你可能不知道的Google Chrome命令行参数
概述: 关于Google Chrome命令行参数(英文叫Google Chrome Command line switches),是Chrome为了实现实验性功能.方便调试. ...
- Error: [ng:areq] Argument 'xxxx' is not a function, got undefined
"Error: [ng:areq] Argument 'keywords' is not a function, got undefined" 代码类似这样的: <div n ...
- 同一个解决方案"引用"其他的项目出现感叹号...
项目A是自己新建的... 但是项目B是"添加"→"现有项目"添加的... 所以项目B引用项目A的时候,引用的项目A显示感叹号... 项目A右击"属性& ...
- Linux统计文件行数
语法:wc [选项] 文件… 说明:该命令统计给定文件中的字节数.字数.行数.如果没有给出文件名,则从标准输入读取.wc同时也给出所有指定文件的总统计数.字是由空格字符区分开的最大字符串. 该命令各选 ...
- wordpress自动清理评论回收站
有时wordpress的垃圾评论实在让人心烦,杂草难除根,footprint吹又生.如果你有心情的话会一个个把垃圾评论放入回收站,但是时间一长,回收站里的东西越堆越多,你可以点击回收站,然后再点一下e ...