python学习笔记之socket(第七天)

     参考文档:

             1、金角大王博客:http://www.cnblogs.com/alex3714/articles/5227251.html

             2、银角大王博客:http://www.cnblogs.com/wupeiqi/articles/5040823.html

一、socket模块:

         socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求。

socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,对于文件用【打开】【读写】【关闭】模式来操作。socket就是该模式的一个实现,socket即是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO、打开、关闭)

socket和file的区别:

          file模块是针对某个指定文件进行【打开】【读写】【关闭】

          socket模块是针对 服务器端 和 客户端Socket 进行【打开】【读写】【关闭】

     1、具体功能介绍 :sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)

参数一:地址簇

  socket.AF_INET IPv4(默认)
  socket.AF_INET6 IPv6

  socket.AF_UNIX 只能够用于单一的Unix系统进程间通信

参数二:类型

  socket.SOCK_STREAM  流式socket , for TCP (默认)
  socket.SOCK_DGRAM   数据报式socket , 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 可靠的连续数据包服务

参数三:协议

  0  (默认)与特定的地址家族相关的协议,如果是 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()

  套接字的文件描述符

举例说明:

1、socket之tcp:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import socket,os,sys

def handle_request(client,address):

    buf = client.recv(1024)
    print(buf,address)
    client.sendall(("your input is %s" % buf).encode('utf-8'))

def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(ip_port)
    sock.listen(5)

    while True:
        print('server is running...')
        connection, address = sock.accept()
        handle_request(connection,address)
        connection.close()

if __name__ == '__main__':
   port = int(sys.argv[1])
   ip_port = ('127.0.0.1',port)
   main()
阻塞server
#!/usr/bin/python
# -*- coding: utf-8 -*-

import socket,os,sys
port = int(sys.argv[1])
ip_port = ('127.0.0.1',port)


while True:
    sk = socket.socket()
    sk.connect(ip_port)
    inp = input('please input the info : ').strip()
    sk.sendall(('%s' % inp ).encode('utf-8'))
    #sk.sendall('nihao'.encode('utf-8'))
    if inp == 'exit':
        break
    server_reply = sk.recv(1024)
    print(server_reply)

    sk.close()
阻塞client

2、socket之udp:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import socket,os,sys

def enc(strr):
    aa = strr.encode('utf-8')
    return aa

if __name__ == '__main__':
   port = int(sys.argv[1])
   ip_port = ('127.0.0.1',port)
   sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
   sock.bind(ip_port)
   while True:
       print('server is running...')
       dat, address = sock.recvfrom(1024)
       data = dat.decode('utf-8')

       send_str = ''
       print(data,address)
       if data == 'exit':
           break
       if data == 'exit':
           break
       elif len(data) == '0':
           send_str = enc('0 ni mei...')
       elif data.find('nihao') >= 0 :
           send_str = enc('hello,baby,nihao')
       elif data.find('sb') >= 0 :
           send_str = enc('sb,to you')
       else:
           send_str = enc('input exit to exit')

       sock.sendto(send_str,address)
   sock.close()
udp-server
#!/usr/bin/python
# -*- coding: utf-8 -*-

import socket,os,sys

port = int(sys.argv[1])
ip_port = ('127.0.0.1',port)
sk = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:

    inp = input('请输入:').strip()
    if inp == 'exit':
        break
    inpp = inp.encode('utf-8') 
    sk.sendto(inpp,ip_port)
    data,address = sk.recvfrom(1024)
    print(data.decode('utf-8'),address)
    
sk.close()
udp-client

3、socket之类ssh执行命令:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import socket,os,sys,subprocess,time

    

def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(ip_port)
    sock.listen(5)    
    
    print('server is running...')
    while True:
        connection, address = sock.accept()
        while True: 
            buf = connection.recv(1024)
            if not buf:
                break
            print("recv cmd:",str(buf,'utf-8'))
            cmd = str(buf,'utf-8').strip()
            cmd_call = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
            cmd_result = cmd_call.stdout.read()
            
            if len(cmd_result) == 0:
                cmd_result = b"cmd execution has no output..."
            ack_msg = "CMD_RESULT_SIZE|%s" % len(cmd_result)
            print(ack_msg)
            connection.send(bytes(ack_msg,'utf8'))
            ack_re = connection.recv(50) 
            print(ack_re)
            connection.send(cmd_result)

        connection.close()
        
if __name__ == '__main__':
   port = int(sys.argv[1])
   ip_port = ('127.0.0.1',port)
   main()
执行命令server
#!/usr/bin/python
# -*- coding: utf-8 -*-

import socket,os,sys
port = int(sys.argv[1])
ip_port = ('127.0.0.1',port)

sk = socket.socket()
sk.connect(ip_port)

while True:
    inp = input('cmd : ').strip()
    if len(inp) == 0:
        continue
    if inp == 'q':
        break
    sk.send(bytes(inp,'utf8'))
    
    server_ack_msg = sk.recv(100)
    cmd_res_msg = server_ack_msg.decode().split("|")
    print(cmd_res_msg)
    if cmd_res_msg[0] == "CMD_RESULT_SIZE":
        cmd_res_size = int(cmd_res_msg[1])
    ack_re = sk.send(b'CMD_RESULT')
    res = ''
    recv_size = 0
    while recv_size < cmd_res_size:
        server_reply = sk.recv(500)
        recv_size += len(server_reply)
        res += str(server_reply,'utf8')
    else:
        print(res)
        print('==========recv done=========')

sk.close()
执行命令client

二、socketserver

socket并不能多并发,只能支持一个用户,socketserver 简化了编写网络服务程序的任务,socketserver是socket的在封装。socketserver在python2中为SocketServer,在python3种取消了首字母大写,改名为socketserver。socketserver中包含了两种类,一种为服务类(server class),一种为请求处理类(request handle class)。前者提供了许多方法:像绑定,监听,运行…… (也就是建立连接的过程) 后者则专注于如何处理用户所发送的数据(也就是事务逻辑)。一般情况下,所有的服务,都是先建立连接,也就是建立一个服务类的实例,然后开始处理用户请求,也就是建立一个请求处理类的实例。
 
socketserver一共有这么几种类型:
 
1. class socketserver.TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)
2. class socketserver.UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)
3. class socketserver.UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)
4. class socketserver.UnixDatagramServer(server_address, RequestHandlerClass,bind_and_activate=True)
 
继承关系图:
+------------+
| BaseServer | 
+------------+
      |
      v
+-----------+        +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+        +------------------+
      |
      v
+-----------+        +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+        +--------------------+
 
如何创建一个socketserver :
 
  1. First, you must create a request handler class by subclassing the BaseRequestHandlerclass and overriding its handle() method; this method will process incoming requests.   
  2. Second, you must instantiate one of the server classes, passing it the server’s address and the request handler class.
  3. Then call the handle_request() orserve_forever() method of the server object to process one or many requests.
  4. Finally, call server_close() to close the socket.
 
  1. 创建一个请求处理的类,并且这个类要继承 BaseRequestHandlerclass ,并且还要重写父类里handle()方法;
  2. 你必须实例化 TCPServer,并且传递server IP和你上面创建的请求处理类,给这个TCPServer;
  3. server.handle_requese()#只处理一个请求,server.server_forever()处理多个一个请求,永远执行
  4. 关闭连接server_close()
 
 
class socketserver.BaseServer(server_address, RequestHandlerClass) 主要有以下方法: 
 
class socketserver.BaseServer(server_address, RequestHandlerClass)
This is the superclass of all Server objects in the module. It defines the interface, given below, but does not implement most of the methods, which is done in subclasses. The two parameters are stored in the respective server_address and RequestHandlerClass attributes.
 
fileno()  #返回文件描述符
Return an integer file descriptor for the socket on which the server is listening. This function is most commonly passed to selectors, to allow monitoring multiple servers in the same process.
 
handle_request() #处理单个请求
Process a single request. This function calls the following methods in order: get_request(), verify_request(), and process_request(). If the user-provided handle() method of the handler class raises an exception, the server’s handle_error() method will be called. If no request is received within timeout seconds, handle_timeout() will be called and handle_request() will return.
 
serve_forever(poll_interval=0.5)  #每0.5秒检查下是否发了shutdown信号,做一些清理工作
Handle requests until an explicit(明确的) shutdown() request. Poll(检查) for shutdown every poll_interval seconds. Ignores the timeout attribute. It also calls service_actions(), which may be used by a subclass or mixin to provide actions specific to a given service. For example, the ForkingMixIn class uses service_actions() to clean up zombie child processes.

Changed in version 3.3: Added service_actions call to the serve_forever method.
 
service_actions() #python3.3里加入,
This is called in the serve_forever() loop. This method can be overridden by subclasses or mixin classes to perform actions specific to a given service, such as cleanup actions.

New in version 3.3.

shutdown() #停掉
Tell the serve_forever() loop to stop and wait until it does.

server_close()#关闭
Clean up the server. May be overridden.
 
address_family #地址蔟
The family of protocols to which the server’s socket belongs. Common examples are socket.AF_INET and socket.AF_UNIX.
 
RequestHandlerClass #请求处理类
The user-provided request handler class; an instance of this class is created for each request.

server_address#IP地址
The address on which the server is listening. The format of addresses varies depending on the protocol family; see the documentation for the socket module for details. For Internet protocols, this is a tuple containing a string giving the address, and an integer port number: ('127.0.0.1', 80), for example.

socket #
The socket object on which the server will listen for incoming requests.

The server classes support the following class variables:
 
allow_reuse_address  #准许重用地址,普通的socket重用地址
Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.
 
request_queue_size  #
The size of the request queue. If it takes a long time to process a single request, any requests that arrive while the server is busy are placed into a queue, up to request_queue_size requests. Once the queue is full, further requests from clients will get a “Connection denied” error. The default value is usually 5, but this can be overridden by subclasses.

socket_type  #协议类型
The type of socket used by the server; socket.SOCK_STREAM and socket.SOCK_DGRAM are two common values.
 
timeout #超时
Timeout duration, measured in seconds, or None if no timeout is desired. If handle_request() receives no incoming requests within the timeout period, the handle_timeout() method is called.

There are various server methods that can be overridden by subclasses of base server classes like TCPServer; these methods aren’t useful to external users of the server object.
 
finish_request()  
Actually processes the request by instantiating RequestHandlerClass and calling its handle() method.
 
 
get_request()  #
Must accept a request from the socket, and return a 2-tuple containing the new socket object to be used to communicate with the client, and the client’s address.

handle_error(request, client_address) #处理错误
This function is called if the handle() method of a RequestHandlerClass instance raises an exception. The default action is to print the traceback to standard output and continue handling further requests.

handle_timeout() #
This function is called when the timeout attribute has been set to a value other than None and the timeout period has passed with no requests being received. The default action for forking servers is to collect the status of any child processes that have exited, while in threading servers this method does nothing.
 
process_request(request, client_address) #单个请求
Calls finish_request() to create an instance of the RequestHandlerClass. If desired, this function can create a new process or thread to handle the request; the ForkingMixIn and ThreadingMixIn classes do this.

server_activate()
Called by the server’s constructor to activate the server. The default behavior for a TCP server just invokes listen() on the server’s socket. May be overridden.

server_bind() #内部调用
Called by the server’s constructor to bind the socket to the desired address. May be overridden.

verify_request(request, client_address) #判断一个请求是否合法
Must return a Boolean value; if the value is True, the request will be processed, and if it’s False, the request will be denied. This function can be overridden to implement access controls for a server. The default implementation always returns True.
socketserver例子:
 使用多进程或多线程实现并发
socket_server:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import socketserver,os,sys


class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        print("new conn:",self.client_address)
        while True:
            data = self.request.recv(1024).strip()
            if not data:
                break  
            print([self.client_address],data)
            self.request.sendall(data.upper())   
    
        
if __name__ == '__main__':
   port = int(sys.argv[1])
   ip_port = ('127.0.0.1',port)

 
   server = socketserver.ThreadingTCPServer(ip_port, MyTCPHandler)   #多线程实现并发
   #server  = socketserver.ForkingTCPServer(ip_port, MyTCPHandler)   #多进程实现并发
   #server = socketserver.TCPServer(ip_port, MyTCPHandler)           #单进程的阻塞模式

   server.serve_forever()
socketserver
socket_client:

连接客户端代码跟原来一样

#!/usr/bin/python
# -*- coding: utf-8 -*-

import socket,os,sys
port = int(sys.argv[1])
ip_port = ('127.0.0.1',port)

sk = socket.socket()
sk.connect(ip_port)

while True:
    inp = input('cmd : ').strip()
    if len(inp) == 0:
        continue
    if inp == 'q':
        break
    sk.send(bytes(inp,'utf8'))
    
    data = sk.recv(1024)
    print("server reply:",str(data,'utf8'))
sk.close()
socketclient
原文地址:https://www.cnblogs.com/wushank/p/8907238.html