本节内容:
Socket语法及相关SocketServer实现多并发 Socket语法及相关socket概念socket本质上就是在2台网络互通的电脑之间,架设一个通道,两台电脑通过这个通道来实现数据的互相传递。 我们知道网络 通信 都 是基于 ip+port 方能定位到目标的具体机器上的具体服务, *** 作系统有0-65535个端口,每个端口都可以独立对外提供服务,如果 把一个公司比做一台电脑 ,那公司的总机号码就相当于ip地址, 每个员工的分机号就相当于端口, 你想找公司某个人,必须 先打电话到总机,然后再转分机 。
建立一个socket必须至少有2端, 一个服务端,一个客户端, 服务端被动等待并接收请求,客户端主动发起请求, 连接建立之后,双方可以互发数据。
A network socket is an endpoint of a connection across a . Today,most communication between computers is based on the ; therefore most network sockets are Internet sockets. More precisely,a socket is a (abstract reference) that a local program can pass to the networking (API) to use the connection,for example "send this data on this socket". Sockets are internally often simply ,which identify which connection to use.
For example,to send "Hello,world!" via 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:
A socket API is an (API),usually provided by the ,that allows application programs to control and use network sockets. Internet socket APIs are usually based on the standard. In the Berkeley sockets standard,sockets are a form of (a file handle),due to the 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 ,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 and a ,much like one end of a telephone connection is the combination of a and a particular . 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 or .
Socket FamilIEs(地址簇)These constants represent the address (and protocol) familIEs,used for the first argument to
. If the constant is not defined then this protocol is unsupported. More constants may be available depending on the sy@R_404_6563@.
These constants represent the socket types,used for the second argument to . More constants may be available depending on the sy@R_404_6563@. (Only and appear to be generally useful.)
Socket 方法
family=AF_INET, type=SOCK_STREAM, proto=0, fileno=NoneCreate a new socket using the given address family,socket type and protocol number. The address family should be
(the default),
, , or . The socket type should be (the default), , or perhaps one of the other
constants. The protocol number is usually zero and may be omitted or in the case where the address family is the protocol should be one of
or . If fileno is specifIEd,the other arguments are ignored,causing the socket with the specifIEd file descriptor to return. Unlike , fileno will return the same socket and not a duplicate. This may help close a detached socket using .familytypeproto
Build a pair of connected socket objects using the given address family,socket type,and protocol number. Address family,and protocol number are as for the function above. The default family is if defined on the platform; otherwise,the default is .
addresstimeoutsource_address
Connect to a TCP service Listening on the Internet address (a 2-tuple ),and return the socket object. This is a higher-level function than : if host is a non-numeric hostname,it will try to resolve it for both and ,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 is used.
If supplIEd, source_address must be a 2-tuple 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.
host, port, family=0, type=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()
套接字的文件描述符
file, offset=0, count=None
The module simplifIEs the task of writing network servers.
There are four basic concrete server classes:
server_address, RequestHandlerClass, bind_and_activate=TrueThis 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
and
. The other parameters are passed to the base class.server_address, bind_and_activate=TrueThis 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
.server_address, bind_and_activate=Trueserver_address,bind_and_activate=TrueThese 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
.These four classes process requests ; 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
and
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:
| | Note that
derives from
,not from — the only difference between an IP and a Unix stream server is the address family,which is simply repeated in both Unix server classes.Forking and threading versions of each type of server can be created using these mix-in classes. For instance,
is created as follows:The mix-in class comes first,since it overrIDes a method defined in
. Setting the varIoUs attributes also changes the behavior of the underlying server mechanism.These classes are pre-defined using the mix-in classes.
Request Handler ObjectsThis is the superclass of all request handler objects. It defines the interface,given below. A concrete request handler subclass must define a new
method,and can overrIDe any of the other methods. A new instance of the subclass is created for each request.Called before the
method to perform any initialization actions required. The default implementation does nothing.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
; the clIEnt address as
; and the server instance as
,in case it needs access to per-server information.
The type of
is different for datagram or stream services. For stream services,
is a socket object; for datagram services,
is a pair of string and socket.
Called after the
method to perform any clean-up actions required. The default implementation does nothing. If
raises an exception,this function will not be called.
Exampleserver sIDe
class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The request handler class for our server.It is instantiated once per connection to the server,and mustoverr<a href="https://m.jb51.cc/tag/ID/" target="_blank" >ID</a>e the handle() method to implement communication to thecl<a href="https://m.jb51.cc/tag/IE/" target="_blank" >IE</a>nt."""def handle(self): # self.request is the TCP socket connected to the cl<a href="https://m.jb51.cc/tag/IE/" target="_blank" >IE</a>nt self.data = self.request.recv(1024).strip() print("{} wrote:".format(self.cl<a href="https://m.jb51.cc/tag/IE/" target="_blank" >IE</a>nt_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 9999server = socketserver.T<a href="https://www.jb51.cc/tag/cps/" target="_blank" >cps</a>erver((HOST,PORT),MyTCPHandler)# Activate the server; this will keep running until you# interrupt the program with Ctrl-Cserver.serve_forever()
clIEnt sIDe
HOST,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 datasock.connect((HOST,PORT))sock.sendall(bytes(data + "\n","utf-8"))# Receive data from the server and shut downreceived = str(sock.recv(1024),"utf-8")
finally:
sock.close()
print("Sent: {}".format(data))
print("Received: {}".format(received))
上面这个例子你会发现,依然不能实现多并发,哈哈,在server端做一下更改就可以了把
<div >
<pre >server = socketserver.ThreadingTcpserver((HOST,MyTCPHandler)
线程与进程http://www.cnblogs.com/alex3714/articles/5230609.HTML
主机管理之paramiko模块学习 http://www.cnblogs.com/wupeiqi/articles/5095821.HTML
作业1:用socketserver继续完善FTP作业
需求:
可以对机器进行分组可以对指定的一组或多组机器执行批量命令,分发文件(发送\接收)纪录 *** 作日志 总结 以上是内存溢出为你收集整理的Python之路,Day8 - Socket编程进阶全部内容,希望文章能够帮你解决Python之路,Day8 - Socket编程进阶所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)