python epoll方式tcp连接回发消息

Posted 6min

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python epoll方式tcp连接回发消息相关的知识,希望对你有一定的参考价值。

# -*- coding:utf-8 -*-
import socket
import select

class testserver():
    def __init__(self):
        self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.serversocket.bind((0.0.0.0, 8889))
        self.serversocket.listen(128)
        self.serversocket.setblocking(0)

    def run(self):
        response = "connecting status: 200"
        epoll = select.epoll()
        epoll.register(self.serversocket.fileno(), select.EPOLLIN)

        try:
            connections = {}
            requests = {}
            responses = {}
            endflag = \n\r\n

            while True:
                events = epoll.poll(1)
                for fid, event in events:
                    if fid == self.serversocket.fileno():
                        connection, address = self.serversocket.accept()
                        connection.setblocking(0)
                        epoll.register(connection.fileno(), select.EPOLLIN)
                        connections[connection.fileno()] = connection
                        requests[connection.fileno()] = ‘‘
                        responses[connection.fileno()] = response.encode()

                    elif event & select.EPOLLIN:
                        try:
                            requests[fid] = connections[fid].recv(1024)
                            if len(str(requests[fid].decode())) == 0:
                                connections[fid].shutdown(socket.SHUT_RDWR)
                                break
                            else:
                                print("2 | ------ : " + str(requests[fid].decode()) + "\n")
                                byteswritten = connections[fid].send(responses[fid])

                            if endflag in requests[fid]:
                                epoll.modify(fid, select.EPOLLOUT)
                                connections[fid].setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 1)
                                print(- * 40 + \n + requests[fid].decode()[:-2])
                        except:
                            continue

                    elif event & select.EPOLLOUT:
                        byteswritten = connections[fid].send(responses[fid])
                        responses[fid] = responses[fid][byteswritten:]
                        if len(responses[fid]) == 0:
                            connections[fid].setsockopt(socket.IPPROTO_TCP, socket.TCP_CORK, 0)
                            epoll.modify(fid, 0)
                            connections[fid].shutdown(socket.SHUT_RDWR)

                    elif event & select.EPOLLHUP:
                        epoll.unregister(fid)
                        connections[fid].close()
                        del connections[fid]

        except:
            print("server excepted ...")
            epoll.unregister(self.serversocket.fileno())
            self.run()

        finally:
            print("server closed ...")


if __name__ == "__main__":
    serv = testserver()
    serv.run()

 

以上是关于python epoll方式tcp连接回发消息的主要内容,如果未能解决你的问题,请参考以下文章

Python3 & 基于TCP的方式实现客户端与服务器端互发消息

epoll实现TCP通信

超详细解读Epoll 多路复用是如何转起来的?

超详细解读Epoll 多路复用是如何转起来的?

Nginx epoll模型详解

提高网络效率的总结