python【第八篇】socket网络编程
内容大纲
1.socke基础
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.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)
发送文件 ,但目前多数情况下并无什么卵用。
SocketServer
The socketserver module simplifies the task of writing network servers.
There are four basic concrete server classes:
- class
socketserver.TCPServer(server_address, RequestHandlerClass, bind_and_activate=True) -
This uses the Internet TCP protocol, which provides for continuous streams of data between the client and server. If bind_and_activate is true, the constructor automatically attempts to invoke
server_bind()andserver_activate(). The other parameters are passed to theBaseServerbase class.
- class
socketserver.UDPServer(server_address, RequestHandlerClass, bind_and_activate=True) -
This uses datagrams, which are discrete packets of information that may arrive out of order or be lost while in transit. The parameters are the same as for
TCPServer.
- class
socketserver.UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True) - class
socketserver.UnixDatagramServer(server_address, RequestHandlerClass,bind_and_activate=True) -
These more infrequently used classes are similar to the TCP and UDP classes, but use Unix domain sockets; they’re not available on non-Unix platforms. The parameters are the same as for
TCPServer.
These four classes process requests synchronously; each request must be completed before the next request can be started. This isn’t suitable if each request takes a long time to complete, because it requires a lot of computation, or because it returns a lot of data which the client is slow to process. The solution is to create a separate process or thread to handle each request; the ForkingMixIn and ThreadingMixIn mix-in classes can be used to support asynchronous behaviour.
There are five classes in an inheritance diagram, four of which represent synchronous servers of four types:
+------------+
| BaseServer |
+------------+
|
v
+-----------+ +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+ +------------------+
|
v
+-----------+ +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+ +--------------------+
Note that UnixDatagramServer derives from UDPServer, not from UnixStreamServer — the only difference between an IP and a Unix stream server is the address family, which is simply repeated in both Unix server classes.
- class
socketserver.ForkingMixIn - class
socketserver.ThreadingMixIn -
Forking and threading versions of each type of server can be created using these mix-in classes. For instance,
ThreadingUDPServeris created as follows:class ThreadingUDPServer(ThreadingMixIn, UDPServer): passThe mix-in class comes first, since it overrides a method defined in
UDPServer. Setting the various attributes also changes the behavior of the underlying server mechanism.
- class
socketserver.ForkingTCPServer - class
socketserver.ForkingUDPServer - class
socketserver.ThreadingTCPServer - class
socketserver.ThreadingUDPServer -
These classes are pre-defined using the mix-in classes.
Request Handler Objects
class
socketserver.BaseRequestHandlerThis is the superclass of all request handler objects. It defines the interface, given below. A concrete request handler subclass must define a new
handle()method, and can override any of the other methods. A new instance of the subclass is created for each request.setup()-
Called before the
handle()method to perform any initialization actions required. The default implementation does nothing.
handle()-
This function must do all the work required to service a request. The default implementation does nothing. Several instance attributes are available to it; the request is available as
self.request; the client address asself.client_address; and the server instance asself.server, in case it needs access to per-server information.The type of
self.requestis different for datagram or stream services. For stream services,self.requestis a socket object; for datagram services,self.requestis a pair of string and socket.
finish()-
Called after the
handle()method to perform any clean-up actions required. The default implementation does nothing. Ifsetup()raises an exception, this function will not be called.# _*_ coding:utf-8 _*_ # __author__ = "ZingP" import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): while True: try: self.data = self.request.recv(1024).strip() print("{}wrote:".format(self.client_address[0])) print(self.data) self.request.send(self.data.upper()) except ConnectionResetError as e: print("error:", e) break if __name__ == "__main__": HOST, PORT = "localhost", 9000 # server = socketserver.TCPServer((HOST, PORT), MyTCPHandler) # server = socketserver.ForkingTCPServer((HOST, PORT), MyTCPHandler) # 多进程 Windows上不好使,Linux好使。 server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) # 多线程 server.serve_forever()
2.socket进阶
2.1模拟ssh
2.1.1server端 1 # _*_ coding:utf-8 _*_ 2 __author__ = "ZingP" 3 4 import socket,os 6 server = socket.socket()
server.bind(("localhost", 9000))
server.listen()
while True:
conn, addr = server.accept()
while True:
print("等待新指令。")
data = conn.recv(1024)
if not data: break
cmd_res = os.popen(data.decode()).read()
print("before send:", len(cmd_res))
if len(cmd_res) == 0:
cmd_res = "cmd has no output..." # cmd 没有返回的数据
conn.send(str(len(cmd_res.encode())).encode("utf-8")) # 把cmd返回的数据大小发给客户端(告诉客户端,我要给你发这么大的数据) # 这里有个坑,就是必须对cmd_res进行encode(),否则会因为中文编码问题,导致发送的数据和接收的数据打印出的大小不一致
conn.send(cmd_res.encode("utf-8")) # cmd返回的数据
print("send done")
server.close()
2.1.2client端
# _*_ coding:utf-8 _*_
__author__ = "ZingP"
import socket
client = socket.socket()
client.connect(("localhost", 9000))
while True:
cmd = input(">>:").strip()
if len(cmd) == 0: continue
client.send(cmd.encode("utf-8"))
cmd_res_size = client.recv(1024) # 第一次先接收即将要接收的数据大小
print("命令结果大小:", cmd_res_size)
received_size = 0 # 初始收到的数据大小为零
received_data = b'' # 初始收到的数据为空
while received_size < int(cmd_res_size.decode()):
data = client.recv(1024)
received_size += len(data) # 累加每次收到的数据大小
received_data += data # 累加每次收到的数据
else:
print("收到数据大小:", received_size)
print(received_data.decode())
client.close()
python【第八篇】socket网络编程的更多相关文章
- Python全栈【Socket网络编程】
Python全栈[socket网络编程] 本章内容: Socket 基于TCP的套接字 基于UDP的套接字 TCP粘包 SocketServer 模块(ThreadingTCPServer源码剖析) ...
- 从零开始学Python第八周:网络编程基础(socket)
Socket网络编程 一,Socket编程 (1)Socket方法介绍 Socket是网络编程的一个抽象概念.通常我们用一个Socket表示"打开了一个网络链接",而打开一个Soc ...
- Python面向对象进阶和socket网络编程-day08
写在前面 上课第八天,打卡: 为什么坚持?想一想当初: 一.面向对象进阶 - 1.反射补充 - 通过字符串去操作一个对象的属性,称之为反射: - 示例1: class Chinese: def __i ...
- Python面向对象进阶和socket网络编程
写在前面 为什么坚持?想一想当初: 一.面向对象进阶 - 1.反射补充 - 通过字符串去操作一个对象的属性,称之为反射: - 示例1: class Chinese: def __init__(self ...
- Python之旅Day8 socket网络编程
socket网络编程 Socket是网络编程的一个抽象概念.通常我们用一个Socket表示“打开了一个网络链接”,而打开一个Socket需要知道目标计算机的IP地址和端口号,再指定协议类型即可.soc ...
- 【python自动化第八篇:网络编程】
一.拾遗 动态导入模块 目的是为了在导入模块的过程中将模块以字符的格式导入. #!/usr/bin/env python # -*- coding:utf-8 -*- #Author:wanghui ...
- Java基础篇Socket网络编程中的应用实例
说到java网络通讯章节的内容,刚入门的学员可能会感到比较头疼,应为Socket通信中一定会伴随有IO流的操作,当然对IO流比较熟练的哥们会觉得这是比较好玩的一章,因为一切都在他们的掌握之中,这样操作 ...
- NO.8:自学python之路------并行socket网络编程
摘要 一到放假就杂事很多,这次的作业比较复杂,做了一个周,进度又拖了.不过结果还不错. 正文 粘包 在上一节中,如果连续发送过多数据,就可能发生粘包.粘包就是两次发送的数据粘在一起被接收,损坏了数据的 ...
- python3.x 基础八:socket网络编程
Socket socket就是一直以来说的“套接字”,用于描述:ip:端口,是通信链的句柄,客户端通过这个句柄进行请求和响应 普通文件的操作顺序:打开-读写-关闭,针对的是文件 socket是特殊的文 ...
- Python之路【第七篇】python基础 之socket网络编程
本篇文章大部分借鉴 http://www.cnblogs.com/nulige/p/6235531.html python socket 网络编程 一.服务端和客户端 BS架构 (腾讯通软件:ser ...
随机推荐
- nyoj 88 汉诺塔(一)【快速幂】
汉诺塔(一) 时间限制:1000 ms | 内存限制:65535 KB 难度:3 描述 在印度,有这么一个古老的传说:在世界中心贝拿勒斯(在印度北部)的圣庙里,一块黄铜板上插着三根宝石针.印度 ...
- 【JAVA - 基础】之反射的原理与应用
一.反射简介 反射机制指的是程序在运行时能够获取自身的信息.在JAVA中,只要给定类的名字,那么就可以通过反射机制来获取类的所有信息. 1.反射的应用 JDBC编程中的:Class.forName(& ...
- jquery_EasyUI的学习
1 Accordion(可折叠标签) 1.1 实例 1.1.1 代码 <html> <head> <meta http-equiv="Content-Type& ...
- Win7无法设置背景图片的快速解决办法
不知道怎么回事,win7电脑突然连个性化设置背景图片的按钮都没了.真操蛋~~~满屏的黑色背景图案,看着实在是不爽. 为了解决这个问题,网上搜索了好长时间,都不尽然! 最后想到了一个超简单的方法就是: ...
- C# 打开PPT文件另存为PPTX
/// <summary> /// rename PPT /// </summary> private static void renamePPT() { //add refe ...
- hdu 5073 Galaxy
题意是给定n个点,让求找到一个点p使得sigma( (a[i] - p) ^ 2 ) 最小,其中a[i]表示第i个点的位置.其中有k个点不用算. 思路:发现这道题其实就是求n-k个点方差. 那么推一下 ...
- display:table- cell属性的练习
display:table- cell属性指让标签元素以表格单元格的形式呈现,类似于td标签.目前IE8+以及其他现代浏览器都是支持此属性的,但是IE6/7只能对你说 sorry了,这一事实也是大大制 ...
- $HTTP_RAW_POST_DATA
这是手册里写的 总是产生变量包含有原始的 POST 数据.否则,此变量仅在碰到未识别 MIME 类型的数据时产生.不过,访问原始 POST 数据的更好方法是 php://input.$HTTP_RAW ...
- Spring MVC返回json数据给Android端
原先做Android项目时,服务端接口一直是别人写的,自己拿来调用一下,但下个项目,接口也要自己搞定了,我想用Spring MVC框架来提供接口,这两天便抽空浅学了一下该框架以及该框架如何返回json ...
- System.Data.DbType的字符串和数据库中字符串类型对应关系
前两天项目中因为历史原因数据库中的一个字段是varchar类型,在做SQL参数化处理时候默认都是DbType.String, 免得查询出现数据转换,于是做类型一致,搜了下对应关系还没找到,只好自己打开 ...