IO多路复用-Select\poll\epoll

IO多路复用-Select\poll\epoll_第1张图片服务端-select:

 

from select import select
from socket import *

s = socket()
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(("0.0.0.0", 8888))
s.listen(3)

rlist = [s]
wlist = []
xlist = []

print("look IO now")
while True:
    rs, ws, xs = select(rlist, wlist, xlist)
    for r in rs:
        if r is s:
            c, addr = r.accept()
            print("Connect from:", addr)
            rlist.append(c)
        else:
            try:
                data = r.recv(1024).decode()
            except Exception as e:
                print(e)
                data = None
            if not data:
                rlist.remove(r)
                r.close()
                continue
            print(data)
            r.send(b"OK")
    for w in ws:
        pass
    for w in ws:
        pass

服务端-poll

from socket import *
from select import *

server_addr = ("127.0.0.1", 8080)
s = socket()
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(server_addr)
s.setblocking(False)
s.listen(3)
p = poll()
p.register(s, POLLIN | POLLERR)
fdmap = {s.fileno(): s}

while True:
    events = p.poll()
    for fd, event in p.poll():
        if fd == s.fileno():
            c, addr = s.accept()
            print("connect from :", addr)
            p.register(c, POLLIN | POLLERR)
            fdmap[c.fileno()] = c
        elif event & POLLIN:
            data = fdmap[fd].recv(1024)
            if not data:
                p.unregister(fdmap[fd])
                fdmap[fd].close()
                del fdmap[fd]
                continue
            print(data)
            fdmap[fd].send(b"ok")

服务端EPOLL

from socket import *
from select import *

server_addr = ("127.0.0.1", 8080)
s = socket()
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(server_addr)
s.setblocking(False)
s.listen(3)
ep = epoll()
ep.register(s, EPOLLIN | EPOLLERR)
fdmap = {s.fileno(): s}

while True:
    events = ep.poll()
    for fd, event in events:
        if fd == s.fileno():
            c, addr = s.accept()
            print("connect from :", addr)
            ep.register(c, EPOLLIN | EPOLLERR)
            fdmap[c.fileno()] = c
        elif event & EPOLLIN:
            data = fdmap[fd].recv(1024)
            if not data:
                ep.unregister(fdmap[fd])
                fdmap[fd].close()
                del fdmap[fd]
                continue
            print(data)
            fdmap[fd].send(b"ok")

客户端:

from socket import *
server_addr = ("192.168.27.189", 8888)
sock = socket()
sock.connect(server_addr)
while True:
    x = input("ok:")
    if not x:
        break
    sock.send(x.encode())
    data = sock.recv(1024)
    print(data)

你可能感兴趣的:(服务器,运维)