pyqt5 http.server代码怎么写
时间: 2024-05-02 11:19:03 浏览: 171
可以通过以下代码来实现简单的 HTTP 服务器:
```
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QIODevice, QByteArray
from PyQt5.QtNetwork import QTcpServer, QHostAddress
class HttpServer(QTcpServer):
def __init__(self, parent=None):
super(HttpServer, self).__init__(parent)
self.newConnection.connect(self.handleRequest)
def handleRequest(self):
client = self.nextPendingConnection()
client.waitForReadyRead()
request = client.readAll().data()
response = self.processRequest(request)
client.write(response)
client.disconnectFromHost()
def processRequest(self, request):
return "HTTP/1.1 200 OK\r\nContent-Length: 13\r\n\r\nHello World!"
if __name__ == '__main__':
app = QApplication(sys.argv)
server = HttpServer()
if not server.listen(QHostAddress.Any, 8000):
print("Could not start server")
sys.exit(1)
print("Server started")
sys.exit(app.exec_())
```
这个简单的 HTTP 服务器使用 PyQt5 编写,监听端口为 8000。当有连接到来时,它会读取到请求消息,然后调用 `processRequest()` 方法来处理请求,最后返回相应消息给客户端。当然,这只是一个简单的示例,实际应用中应该会更复杂。
阅读全文
相关推荐















