#!/usr/bin/python # -*- coding:utf-8 -*- import Socket, select EOL1 = b'\n\n' EOL2 = b'\n\r\n' response = b'Http/1.0
- #!/usr/bin/python
- # -*- coding:utf-8 -*-
-
- import Socket, select
-
- EOL1 = b'\n\n'
- EOL2 = b'\n\r\n'
- response = b'Http/1.0 200 OK\r\nDate: Mon, 1 Jan 1996 01:01:01 GMT\r\n'
- response += b'Content-Type: text/plain\r\nContent-Length: 13\r\n\r\n'
- response += b'Hello, world!'
-
- serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- serversocket.bind(('0.0.0.0', 8080))
- serversocket.listen(1)
- serversocket.setblocking(0)
-
- epoll = select.epoll()
- epoll.reGISter(serversocket.fileno(), select.EPOLLIN)
-
- try:
- connections = {}; requests = {}; responses = {}
-
- while True:
- events = epoll.poll(1)
-
- for fileno, event in events:
- if fileno == serversocket.fileno():
- connection, address = serversocket.accept()
- connection.setblocking(0)
- epoll.register(connection.fileno(), select.EPOLLIN)
-
- connections[connection.fileno()] = connection
- requests[connection.fileno()] = b''
- responses[connection.fileno()] = response
-
- elif event & select.EPOLLIN:
- requests[fileno] += connections[fileno].recv(1024)
-
- if EOL1 in requests[fileno] or EOL2 in requests[fileno]:
- epoll.modify(fileno, select.EPOLLOUT)
- print('-'*40 + '\n' + requests[fileno].decode()[:-2])
-
- elif event & select.EPOLLOUT:
- byteswritten = connections[fileno].send(responses[fileno])
- responses[fileno] = responses[fileno][byteswritten:]
-
- if len(responses[fileno]) == 0:
- epoll.modify(fileno, 0)
- connections[fileno].shutdown(socket.SHUT_RDWR)
-
- elif event & select.EPOLLHUP:
- epoll.unregister(fileno)
- connections[fileno].close()
- del connections[fileno]
-
- finally:
- epoll.unregister(serversocket.fileno())
- epoll.close()
- serversocket.close()
--结束END--
本文标题: how to use linux epo
本文链接: https://lsjlt.com/news/183468.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0