Python之网络编程 Socket编程
本节内容:
- Socket语法及相关
- SocketServer实现多并发
Socket语法及相关
socket概念
socket本质上就是在2台网络互通的电脑之间,架设一个通道,两台电脑通过这个通道来实现数据的互相传递。 我们知道网络 通信 都 是基于 ip+port 方能定位到目标的具体机器上的具体服务,操作系统有0-65535个端口,每个端口都可以独立对外提供服务,如果 把一个公司比做一台电脑 ,那公司的总机号码就相当于ip地址, 每个员工的分机号就相当于端口, 你想找公司某个人,必须 先打电话到总机,然后再转分机 。
建立一个socket必须至少有2端, 一个服务端,一个客户端, 服务端被动等待并接收请求,客户端主动发起请求, 连接建立之后,双方可以互发数据。
A network socket is an endpoint of a connection across a computer network. Today, most communication between computers is based on the Internet Protocol; therefore most network sockets are Internet sockets. More precisely, a socket is a handle (abstract reference) that a local program can pass to the networking application programming interface (API) to use the connection, for example "send this data on this socket". Sockets are internally often simply integers, which identify which connection to use.
For example, to send "Hello, world!" via TCP to port 80 of the host with address 1.2.3.4, one might get a socket, connect it to the remote host, send the string, then close the socket:
1
2
3
4
|
Socket socket = getSocket( type = "TCP" ) connect(socket, address = "1.2.3.4" , port = "80" ) send(socket, "Hello, world!" ) close(socket) |
A socket API is an application programming interface (API), usually provided by the operating system, that allows application programs to control and use network sockets. Internet socket APIs are usually based on the Berkeley sockets standard. In the Berkeley sockets standard, sockets are a form of file descriptor (a file handle), due to the Unix philosophy that "everything is a file", and the analogies between sockets and files: you can read, write, open, and close both. In practice the differences mean the analogy is strained, and one instead use different interfaces (send and receive) on a socket. In inter-process communication, each end will generally have its own socket, but these may use different APIs: they are abstracted by the network protocol.
A socket address is the combination of an IP address and a port number, much like one end of a telephone connection is the combination of a phone number and a particular extension. Sockets need not have an address (for example for only sending data), but if a program binds a socket to an address, the socket can be used to receive data sent to that address. Based on this address, internet sockets deliver incoming data packets to the appropriate application process or thread.
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 theBaseServer
base 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,
ThreadingUDPServer
is 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.
BaseRequestHandler
This 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.request
is different for datagram or stream services. For stream services,self.request
is a socket object; for datagram services,self.request
is 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.socketserver.TCPServer
Exampleserver side
12345678910111213141516171819202122232425262728import
socketserver
class
MyTCPHandler(socketserver.BaseRequestHandler):
"""
The request handler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def
handle(
self
):
# self.request is the TCP socket connected to the client
self
.data
=
self
.request.recv(
1024
).strip()
print
(
"{} wrote:"
.
format
(
self
.client_address[
0
]))
print
(
self
.data)
# just send back the same data, but upper-cased
self
.request.sendall(
self
.data.upper())
if
__name__
=
=
"__main__"
:
HOST, PORT
=
"localhost"
,
9999
# Create the server, binding to localhost on port 9999
server
=
socketserver.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
client side
123456789101112131415161718192021import
socket
import
sys
HOST, PORT
=
"localhost"
,
9999
data
=
" "
.join(sys.argv[
1
:])
# Create a socket (SOCK_STREAM means a TCP socket)
sock
=
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try
:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data
+
"\n"
,
"utf-8"
))
# Receive data from the server and shut down
received
=
str
(sock.recv(
1024
),
"utf-8"
)
finally
:
sock.close()
print
(
"Sent: {}"
.
format
(data))
print
(
"Received: {}"
.
format
(received))
上面这个例子你会发现,依然不能实现多并发,哈哈,在server端做一下更改就可以了
把
1server
=
socketserver.TCPServer((HOST, PORT), MyTCPHandler)
改成
1server
=
socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)
线程与进程
https://www.cnblogs.com/shuai1991/p/10920096.html
主机管理之paramiko模块学习
http://www.cnblogs.com/wupeiqi/articles/5095821.html
作业1:用socketserver继续完善FTP作业
作业2:开发一个批量主机管理工具
需求:
- 可以对机器进行分组
- 可以对指定的一组或多组机器执行批量命令,分发文件(发送\接收)
- 纪录操作日志
Python之网络编程 Socket编程的更多相关文章
- Day8 - Python网络编程 Socket编程
Python之路,Day8 - Socket编程进阶 本节内容: Socket语法及相关 SocketServer实现多并发 Socket语法及相关 socket概念 socket本质上就是在2台 ...
- Python之路,Day8 - Socket编程进阶
Python之路,Day8 - Socket编程进阶 本节内容: Socket语法及相关 SocketServer实现多并发 Socket语法及相关 socket概念 socket本质上就是在2台 ...
- 【爬坑】Python 3.6 在 Socket 编程时出现类型错误 TypeError: a bytes-like object is required, not 'str'
1. 问题描述 Python 3.6 在 Socket 编程时出现错误如下 Traceback (most recent call last): File "F:/share/IdeaPro ...
- python网络编程-socket编程
一.服务端和客户端 BS架构 (腾讯通软件:server+client) CS架构 (web网站) C/S架构与socket的关系: 我们学习socket就是为了完成C/S架构的开发 二.OSI七层 ...
- Day10 Python网络编程 Socket编程
一.客户端/服务器架构 1.C/S架构,包括: 1.硬件C/S架构(打印机) 2.软件C/S架构(web服务)[QQ,SSH,MySQL,FTP] 2.C/S架构与socket的关系: 我们学习soc ...
- Python的网络编程 Socket编程
Socket是进程间通信的一种方式,与其他进程间通信的一个主要不同是:能实现不同主机间的进程间通信,网络上各种各样的服务大多都是基于Socket来完成通信的,要解决网络上两台主机间的通信问题,首先要唯 ...
- Python(七)Socket编程、IO多路复用、SocketServer
本章内容: Socket IO多路复用(select) SocketServer 模块(ThreadingTCPServer源码剖析) Socket socket通常也称作"套接字" ...
- 网络编程——socket编程
一.客户端/服务端架构 1.硬件C/S架构(打印机) 2.软件C/S架构 互联网企业处处是C/S架构 C/S架构与socket的关系:学习socket就是为了完成C/S架构的开发 二.OSI七层 一个 ...
- HUST-计算机网络实验-socket编程
随笔---HUST计网实验:socket编程 博主大三在读,第一次写随笔,水平有限,就当记录一下学习的过程,顺便面试前复习项目的时候看看. 实验要求: 编写一个 Web 服务器软件,要求如下: 基本要 ...
- python网络编程socket编程(TCP、UDP客户端服务器)
摘录 python核心编程 使用socket()模块函数创建套接字——通信端点 >>> from socket import * >>> tcpSock = soc ...
随机推荐
- JavaScript选择器和节点操作
感谢:链接(视频讲解很清晰) 下文中讲解用到Chrome中的console调试台,如果不懂最好先看一下:链接 JavaScript选择器 作用:选取html中的标签等内容,最重要的还是为节点的操作(增 ...
- Linux基础:pkill命令总结
本文只总结一些常用的用法,更详细的说明见man pkill和pkill --help. pkill命令 pkill命令:通过进程名杀死进程. 语法格式 Usage: pkill [options] & ...
- python基础整理(2)
布尔表达式与其余值的替换 值的测试 Python不仅仅可以使用布尔型变量作为条件,它可以直接在if中使用任何表达式作为条件: 大部分表达式的值都会被当作True,但以下表达式值会被当作False: F ...
- 【01JMeter基础】测试计划
测试计划 整个脚本的集合根目录,所有线程组集合的承载,可以添加线程组.测试片段.非测试元件.配置元件.监听器.定时器.前置/后置处理起器.断言等 一.用户自定义变量 可以使用在所有的线程组中,通过${ ...
- 【String注解驱动开发】面试官让我说说:如何使用FactoryBean向Spring容器中注册bean?
写在前面 在前面的文章中,我们知道可以通过多种方式向Spring容器中注册bean.可以使用@Configuration结合@Bean向Spring容器中注册bean:可以按照条件向Spring容器中 ...
- 利用requets库采集蘑菇租房网的租房信息
前言:对于我们任何一个漂泊在外的打工者,租房似乎都是我们必经的一个经历,对于我们而言,选择性价比最高,最适合自己的房源至关重要,本文就将利用爬虫技术采集蘑菇租房网上指定的房源信息,后续可以利用这些信息 ...
- Redis持久性——RDB和AOF
Redis持久性 Redis提供了不同的持久性选项: RDB持久性以指定的时间间隔执行数据集的时间点快照. AOF持久性记录服务器接收的每个写入操作,将在服务器启动时再次播放,重建原始数据集.使用与R ...
- asp .net core发布订阅kafka
Kafka是一种高吞吐量的分布式发布订阅消息系统,有如下特性: 通过O的磁盘数据结构提供消息的持久化,这种结构对于即使数以TB的消息存储也能够保持长时间的稳定性能. 高吞吐量:即使是非常普通的硬件Ka ...
- Chrome插件Postman的数据目录存储位置,记一次重装系统后找回postman数据的过程...
有次重装系统到一块新的SSD磁盘,很多数据都做了备份就是忘记将Chrome插件Postman的数据做备份,导致重装后找不到以前定义的那些Collections.悔恨之余想到既然我原来的C盘还在,为何不 ...
- 关于阿里云服务器Linux安装Tomcat后,外网不能访问解决方案
这里需要提及三个方面的问题 第一个方面:Linux上启动防火墙的问题 当下比较流行的Linux镜像是CentOS,所以防火墙也随之变成了firewall,那么怎么操作这个防火墙呢? #停止fi ...