您好,登錄后才能下訂單哦!
怎么在python中利用epoll實(shí)現(xiàn)一個(gè)服務(wù)端?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
如下所示:
#!/usr/bin/python # -*- coding: UTF-8 -*- import socket import select send_data = "hello world!" send_len = len(send_data) recv_len = 1024 tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) addr = ("0.0.0.0", 8765) tcp_socket.bind(addr) tcp_socket.listen(5) tcp_socket.setblocking(False) epoll = select.epoll() '''(邊緣觸發(fā))select.EPOLLIN | select.EPOLLET''' epoll.register(tcp_socket.fileno(), select.EPOLLIN) '''因?yàn)閑poll返回的觸發(fā)事件對(duì)應(yīng)的是套接字文件描述符,所以需要在字典中加入對(duì)應(yīng)關(guān)系''' fd_to_socket = {tcp_socket.fileno():tcp_socket} while True : events = epoll.poll(-1) for fd, event in events: fd_socket = fd_to_socket[fd] if fd == tcp_socket.fileno(): while True: try: new_socket, new_addr = fd_socket.accept() except socket.error as e: (errno, err_msg) = e print errno print err_msg if errno == 11: break print "new accpet:", new_addr new_socket.setblocking(False) new_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) epoll.register(new_socket.fileno(), select.EPOLLIN) fd_to_socket[new_socket.fileno()] = new_socket elif event&select.EPOLLIN: recv_datas = [] recd = 0 while (recd < recv_len): try: recv_data = fd_socket.recv(recv_len - recd) '''處理讀的正常關(guān)閉''' if recv_data == "": print "close socket" epoll.unregister(fd) fd_to_socket[fd].close() del fd_to_socket[fd] break else: recv_datas.append(recv_data) recd = recd + len(recv_data) '''處理異常關(guān)閉(EAGAIN,EINTR)''' except socket.error as e: (errno, err_msg) = e print errno print err_msg '''因?yàn)橛玫乃接|發(fā),EAGAIN我們跳出循環(huán),等待下次觸發(fā)再讀就好了''' if errno == 11: break '''軟中斷打斷了還要繼續(xù)讀''' elif errno == 4: continue '''其它錯(cuò)誤我們直接關(guān)閉套接字''' else: print "close socket" epoll.unregister(fd) fd_to_socket[fd].close() del fd_to_socket[fd] break print repr(recv_datas) total_send = 0 while total_send < send_len: sent = fd_socket.send(send_data[total_send:]) if sent == 0: print "close socket" epoll.unregister(fd) fd_to_socket[fd].close() del fd_to_socket[fd] break else: print repr(send_data[total_send:]) total_send = total_send + sent
其實(shí)這里的異常處理我們也可以用
except IOError as e: print e.errno print e.strerror
看完上述內(nèi)容,你們掌握怎么在python中利用epoll實(shí)現(xiàn)一個(gè)服務(wù)端的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。