def bind(self, address): # real signature unknown; restored from __doc__"""bind(address)Bind the socket to a local address. For IP sockets, the address is apair (host, port); the host must refer to the local host. For raw packetsockets the address is a tuple (ifname, proto [,pkttype [,hatype]])"""
'''將套接字綁定到本地地址。是一個IP套接字的地址對(主機、端口),主機必須參考本地主機。'''passdef close(self): # real signature unknown; restored from __doc__"""close()Close the socket. It cannot be used after this call."""'''關閉socket'''passdef connect(self, address): # real signature unknown; restored from __doc__"""connect(address)Connect the socket to a remote address. For IP sockets, the addressis a pair (host, port)."""'''將套接字連接到遠程地址。IP套接字的地址'''passdef connect_ex(self, address): # real signature unknown; restored from __doc__"""connect_ex(address) -> errnoThis is like connect(address), but returns an error code (the errno value)instead of raising an exception when an error occurs."""passdef detach(self): # real signature unknown; restored from __doc__"""detach()Close the socket object without closing the underlying file descriptor.The object cannot be used after this call, but the file descriptorcan be reused for other purposes. The file descriptor is returned."""
'''關閉套接字對象沒有關閉底層的文件描述符。'''passdef fileno(self): # real signature unknown; restored from __doc__"""fileno() -> integerReturn the integer file descriptor of the socket."""'''返回整數的套接字的文件描述符。'''return 0def getpeername(self): # real signature unknown; restored from __doc__"""getpeername() -> address infoReturn the address of the remote endpoint. For IP sockets, the addressinfo is a pair (hostaddr, port)."""'''返回遠程端點的地址。IP套接字的地址'''passdef getsockname(self): # real signature unknown; restored from __doc__"""getsockname() -> address infoReturn the address of the local endpoint. For IP sockets, the addressinfo is a pair (hostaddr, port)."""'''返回遠程端點的地址。IP套接字的地址'''passdef getsockopt(self, level, option, buffersize=None): # real signature unknown; restored from __doc__"""getsockopt(level, option[, buffersize]) -> valueGet a socket option. See the Unix manual for level and option.If a nonzero buffersize argument is given, the return value is astring of that length; otherwise it is an integer."""'''得到一個套接字選項'''passdef gettimeout(self): # real signature unknown; restored from __doc__"""gettimeout() -> timeoutReturns the timeout in seconds (float) associated with socket operations. A timeout of None indicates that timeouts on socket operations are disabled."""'''返回的超時秒數(浮動)與套接字相關聯'''return timeoutdef ioctl(self, cmd, option): # real signature unknown; restored from __doc__"""ioctl(cmd, option) -> longControl the socket with WSAIoctl syscall. Currently supported 'cmd' values areSIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval)."""return 0def listen(self, backlog=None): # real signature unknown; restored from __doc__"""listen([backlog])Enable a server to accept connections. If backlog is specified, it must beat least 0 (if it is lower, it is set to 0); it specifies the number ofunaccepted connections that the system will allow before refusing newconnections. If not specified, a default reasonable value is chosen."""'''使服務器能夠接受連接。'''passdef recv(self, buffersize, flags=None): # real signature unknown; restored from __doc__"""recv(buffersize[, flags]) -> dataReceive up to buffersize bytes from the socket. For the optional flagsargument, see the Unix manual. When no data is available, block untilat least one byte is available or until the remote end is closed. Whenthe remote end is closed and all data is read, return the empty string."""
'''當沒有數據可用,阻塞,直到至少一個字節是可用的或遠程結束之前關閉。'''passdef recvfrom(self, buffersize, flags=None): # real signature unknown; restored from __doc__"""recvfrom(buffersize[, flags]) -> (data, address info)Like recv(buffersize, flags) but also return the sender's address info."""passdef recvfrom_into(self, buffer, nbytes=None, flags=None): # real signature unknown; restored from __doc__"""recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info."""passdef recv_into(self, buffer, nbytes=None, flags=None): # real signature unknown; restored from __doc__"""recv_into(buffer, [nbytes[, flags]]) -> nbytes_readA version of recv() that stores its data into a buffer rather than creating a new string. Receive up to buffersize bytes from the socket. If buffersize is not specified (or 0), receive up to the size available in the given buffer.See recv() for documentation about the flags."""passdef send(self, data, flags=None): # real signature unknown; restored from __doc__"""send(data[, flags]) -> countSend a data string to the socket. For the optional flagsargument, see the Unix manual. Return the number of bytessent; this may be less than len(data) if the network is busy."""'''發送一個數據字符串到套接字。'''passdef sendall(self, data, flags=None): # real signature unknown; restored from __doc__"""sendall(data[, flags])Send a data string to the socket. For the optional flagsargument, see the Unix manual. This calls send() repeatedlyuntil all data is sent. If an error occurs, it's impossibleto tell how much data has been sent."""'''發送一個數據字符串到套接字,直到所有數據發送完成'''passdef sendto(self, data, flags=None, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """sendto(data[, flags], address) -> countLike send(data, flags) but allows specifying the destination address.For IP sockets, the address is a pair (hostaddr, port)."""passdef setblocking(self, flag): # real signature unknown; restored from __doc__"""setblocking(flag)Set the socket to blocking (flag is true) or non-blocking (false).setblocking(True) is equivalent to settimeout(None);setblocking(False) is equivalent to settimeout(0.0)."""
'''是否阻塞(默認True),如果設置False,那么accept和recv時一旦無數據,則報錯。'''passdef setsockopt(self, level, option, value): # real signature unknown; restored from __doc__"""setsockopt(level, option, value)Set a socket option. See the Unix manual for level and option.The value argument can either be an integer or a string."""passdef settimeout(self, timeout): # real signature unknown; restored from __doc__"""settimeout(timeout)Set a timeout on socket operations. 'timeout' can be a float,giving in seconds, or None. Setting a timeout of None disablesthe timeout feature and is equivalent to setblocking(1).Setting a timeout of zero is the same as setblocking(0)."""passdef share(self, process_id): # real signature unknown; restored from __doc__"""share(process_id) -> bytesShare the socket with another process. The target process idmust be provided and the resulting bytes object passed to the targetprocess. There the shared socket can be instantiated by callingsocket.fromshare()."""return b""def shutdown(self, flag): # real signature unknown; restored from __doc__"""shutdown(flag)Shut down the reading side of the socket (flag == SHUT_RD), the writing sideof the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR)."""passdef _accept(self): # real signature unknown; restored from __doc__"""_accept() -> (integer, address info)Wait for an incoming connection. Return a new socket file descriptorrepresenting the connection, and the address of the client.For IP sockets, the address info is a pair (hostaddr, port)."""pass
注:擼主知道大家懶,所以把全部功能的中文標記在每個功能的下面啦。下面擼主列一些經常用到的吧
# Baseserver
class BaseServer:"""Base class for server classes.Methods for the caller:- __init__(server_address, RequestHandlerClass)- serve_forever(poll_interval=0.5)- shutdown()- handle_request() # if you do not use serve_forever()- fileno() -> int # for select()Methods that may be overridden:- server_bind()- server_activate()- get_request() -> request, client_address- handle_timeout()- verify_request(request, client_address)- server_close()- process_request(request, client_address)- shutdown_request(request)- close_request(request)- handle_error()Methods for derived classes:- finish_request(request, client_address)Class variables that may be overridden by derived classes orinstances:- timeout- address_family- socket_type- allow_reuse_addressInstance variables:- RequestHandlerClass- socket"""timeout = Nonedef __init__(self, server_address, RequestHandlerClass):"""Constructor. May be extended, do not override."""self.server_address = server_addressself.RequestHandlerClass = RequestHandlerClassself.__is_shut_down = threading.Event()self.__shutdown_request = Falsedef server_activate(self):"""Called by constructor to activate the server.May be overridden."""passdef serve_forever(self, poll_interval=0.5):"""Handle one request at a time until shutdown.Polls for shutdown every poll_interval seconds. Ignoresself.timeout. If you need to do periodic tasks, do them inanother thread."""self.__is_shut_down.clear()try:while not self.__shutdown_request:# XXX: Consider using another file descriptor or# connecting to the socket to wake this up instead of# polling. Polling reduces our responsiveness to a# shutdown request and wastes cpu at all other times.r, w, e = _eintr_retry(select.select, [self], [], [],poll_interval)if self in r:self._handle_request_noblock()finally:self.__shutdown_request = Falseself.__is_shut_down.set()def shutdown(self):"""Stops the serve_forever loop.Blocks until the loop has finished. This must be called whileserve_forever() is running in another thread, or it willdeadlock."""self.__shutdown_request = Trueself.__is_shut_down.wait()# The distinction between handling, getting, processing and# finishing a request is fairly arbitrary. Remember:## - handle_request() is the top-level call. It calls# select, get_request(), verify_request() and process_request()# - get_request() is different for stream or datagram sockets# - process_request() is the place that may fork a new process# or create a new thread to finish the request# - finish_request() instantiates the request handler class;# this constructor will handle the request all by itselfdef handle_request(self):"""Handle one request, possibly blocking.Respects self.timeout."""# Support people who used socket.settimeout() to escape# handle_request before self.timeout was available.timeout = self.socket.gettimeout()if timeout is None:timeout = self.timeoutelif self.timeout is not None:timeout = min(timeout, self.timeout)fd_sets = _eintr_retry(select.select, [self], [], [], timeout)if not fd_sets[0]:self.handle_timeout()returnself._handle_request_noblock()def _handle_request_noblock(self):"""Handle one request, without blocking.I assume that select.select has returned that the socket isreadable before this function was called, so there should beno risk of blocking in get_request()."""try:request, client_address = self.get_request()except socket.error:returnif self.verify_request(request, client_address):try:self.process_request(request, client_address)except:self.handle_error(request, client_address)self.shutdown_request(request)def handle_timeout(self):"""Called if no new request arrives within self.timeout.Overridden by ForkingMixIn."""passdef verify_request(self, request, client_address):"""Verify the request. May be overridden.Return True if we should proceed with this request."""return Truedef process_request(self, request, client_address):"""Call finish_request.Overridden by ForkingMixIn and ThreadingMixIn."""self.finish_request(request, client_address)self.shutdown_request(request)def server_close(self):"""Called to clean-up the server.May be overridden."""passdef finish_request(self, request, client_address):"""Finish one request by instantiating RequestHandlerClass."""self.RequestHandlerClass(request, client_address, self)def shutdown_request(self, request):"""Called to shutdown and close an individual request."""self.close_request(request)def close_request(self, request):"""Called to clean up an individual request."""passdef handle_error(self, request, client_address):"""Handle an error gracefully. May be overridden.The default is to print a traceback and continue."""print '-'*40print 'Exception happened during processing of request from',print client_addressimport tracebacktraceback.print_exc() # XXX But this goes to stderr!print '-'*40
# TCP server
class TCPServer(BaseServer):"""Base class for various socket-based server classes.Defaults to synchronous IP stream (i.e., TCP).Methods for the caller:- __init__(server_address, RequestHandlerClass, bind_and_activate=True)- serve_forever(poll_interval=0.5)- shutdown()- handle_request() # if you don't use serve_forever()- fileno() -> int # for select()Methods that may be overridden:- server_bind()- server_activate()- get_request() -> request, client_address- handle_timeout()- verify_request(request, client_address)- process_request(request, client_address)- shutdown_request(request)- close_request(request)- handle_error()Methods for derived classes:- finish_request(request, client_address)Class variables that may be overridden by derived classes orinstances:- timeout- address_family- socket_type- request_queue_size (only for stream sockets)- allow_reuse_addressInstance variables:- server_address- RequestHandlerClass- socket"""address_family = socket.AF_INETsocket_type = socket.SOCK_STREAMrequest_queue_size = 5allow_reuse_address = Falsedef __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):"""Constructor. May be extended, do not override."""BaseServer.__init__(self, server_address, RequestHandlerClass)self.socket = socket.socket(self.address_family,self.socket_type)if bind_and_activate:try:self.server_bind()self.server_activate()except:self.server_close()raisedef server_bind(self):"""Called by constructor to bind the socket.May be overridden."""if self.allow_reuse_address:self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)self.socket.bind(self.server_address)self.server_address = self.socket.getsockname()def server_activate(self):"""Called by constructor to activate the server.May be overridden."""self.socket.listen(self.request_queue_size)def server_close(self):"""Called to clean-up the server.May be overridden."""self.socket.close()def fileno(self):"""Return socket file number.Interface required by select()."""return self.socket.fileno()def get_request(self):"""Get the request and client address from the socket.May be overridden."""return self.socket.accept()def shutdown_request(self, request):"""Called to shutdown and close an individual request."""try:#explicitly shutdown. socket.close() merely releases#the socket and waits for GC to perform the actual close.request.shutdown(socket.SHUT_WR)except socket.error:pass #some platforms may raise ENOTCONN hereself.close_request(request)def close_request(self, request):"""Called to clean up an individual request."""request.close()
# ThreadingMixIn
class ThreadingMixIn:"""Mix-in class to handle each request in a new thread."""# Decides how threads will act upon termination of the# main processdaemon_threads = Falsedef process_request_thread(self, request, client_address):"""Same as in BaseServer but as a thread.In addition, exception handling is done here."""try:self.finish_request(request, client_address)self.shutdown_request(request)except:self.handle_error(request, client_address)self.shutdown_request(request)def process_request(self, request, client_address):"""Start a new thread to process the request."""t = threading.Thread(target = self.process_request_thread,args = (request, client_address))t.daemon = self.daemon_threadst.start()
# SocketServer.BaseRequestHandler
class BaseRequestHandler:"""Base class for request handler classes.This class is instantiated for each request to be handled. Theconstructor sets the instance variables request, client_addressand server, and then calls the handle() method. To implement aspecific service, all you need to do is to derive a class whichdefines a handle() method.The handle() method can find the request as self.request, theclient address as self.client_address, and the server (in case itneeds access to per-server information) as self.server. Since aseparate instance is created for each request, the handle() methodcan define arbitrary other instance variariables."""def __init__(self, request, client_address, server):self.request = requestself.client_address = client_addressself.server = serverself.setup()try:self.handle()finally:self.finish()def setup(self):passdef handle(self):passdef finish(self):pass