標籤:python epoll select linux socket
伺服器端:
#-*- coding:utf8 -*-import socketimport selectimport osaddress = "0.0.0.0"port = 10001sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)def main(): global address,port,sock epoll = select.epoll() #擷取建立好的sock的檔案描述符 fd = sock.fileno() sock.bind((address,port)) sock_dict = {} sock_dict[fd] = sock #對該sock進行註冊 epoll.register(fd,select.EPOLLIN) sock.listen(5) while True: events = epoll.poll(1) for fileno,event in events: #擷取到的檔案描述符和sock的相同就說明是一個新的串連 if fileno == fd: (client,address) = sock.accept() print address client.setblocking(0) #將新的串連進行註冊,用來接收訊息 epoll.register(client.fileno(),select.EPOLLIN) sock_dict[client.fileno()] = client elif event & select.EPOLLIN: print "fileno:",fileno data = sock_dict[fileno].recv(128) if data == '你好': print "Data:",data.decode('UTF-8') sock_dict[fileno].send("你好") elif len(data) == 0: print "線路%d已下線"%fileno epoll.unregister(fileno) else: print "Data:",dataif __name__ == '__main__': main()
用戶端:
#coding: UTF-8 import socketimport selectaddress = "127.0.0.1"port = 10001sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)def main(): global address,port,sock sock.connect((address,port)) epoll = select.epoll() fd = sock.fileno() #這裡的epoll註冊只是用來非同步接收服務端發過來的訊息 epoll.register(fd,select.EPOLLIN) while True: events = epoll.poll(1) for fileno,event in events: if fileno == fd: if event & select.EPOLLIN: data = sock.recv(128) print data data = raw_input(">") if data == 'q': break elif data == '': print "不能發送空訊息" continue sock.send(data) sock.close()main()
python 使用epoll非同步處理多個用戶端的串連