python 实现多任务的四种巧妙的非阻塞服务器

第一种方式:非阻塞的服务器

import socket
''' 我把它称之为一直询问的方式!一直循环列表'''
class Webserver():
    def __init__(self):
            #初始化数据
        self.socker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            #短时间内请求不会ip占用
        self.socker.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socker.bind(('', 8888))
        self.socker.listen(128)
        self.li=list()          #list类
    def server(self):
        while True:
            try:
                sock, adress = self.socker.accept()
                sock.send('你好!'.encode())
                print(adress)
                self.li.append(sock)
                self.re_server(sock)
            except Exception as e:
                pass
    def re_server(self,sock):
        while True:
            try:
                for sock in self.li:
                        # 会一直接受数据。直至循环 但是不能退出,对方停止连接就会报错,除非异常处理
                    data = sock.recv(1024).decode()
                    if data:
                        print(data)
                        sock.send('你好!'.encode())
                    else:
                        sock.close()
                        self.li.remove(sock)
            except Exception as e:
                break
                pass





if __name__ == '__main__':
    we = Webserver()
    we.server()
#第二种非阻塞服务器
import socket

#设置为非阻塞,自己设置
class Webserver():
    def __init__(self):
        self.socker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socker.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socker.bind(('', 8888))
        self.socker.listen(128)
        self.socker.setblocking(False) #设置为非阻塞,需要注意,一定要捕捉异常!不然会报错
        
        
    def server(self):
        while True:
            try:
                sock, adress = self.socker.accept()
                sock.send('你好!'.encode())
                print(adress)
                sock.setblocking(False) #将阻塞设置为非阻塞
                self.re_server(sock)
            except BlockingIOError as e:
                pass
    def re_server(self,sock):
        while True:
            try:
                data = sock.recv(1024).decode()
                if data:
                    print(data)
                    sock.send('你好!'.encode())
                else:
                    sock.close()
                    self.li.remove(sock)

            except BlockingIOError as e:
                pass

            except Exception as e:
                print (e)  # [Errno 9] Bad file descriptor你在客户端创建了一个 socket,发送后服务器就关闭了对应的连接,所以再次 send 会报错
                break



if __name__ == '__main__':
    we = Webserver()
    we.server()

  

posted @ 2018-04-21 23:11  十七楼的羊  阅读(1452)  评论(0编辑  收藏  举报