在Qt中搭建服务器,你可以使用Qt的网络模块,特别是`QServerSocket`类来创建一个TCP或UDP服务器。以下是一个简单的TCP服务器示例,演示了如何使用Qt搭建一个基本的服务器:
1. 添加网络模块:
在你的Qt项目中,确保添加了`QtNetwork`模块。
2. 创建服务器类:
创建一个继承自`QTcpServer`的类,并重写`newConnection()`方法来处理新连接。
3. 运行服务器:
在主函数中,创建你的服务器类的实例,并调用`listen()`方法来启动服务器。
以下是一个简单的TCP服务器示例代码:
```cpp
include
include
include
include
class MyServer : public QTcpServer {
Q_OBJECT
public:
MyServer(QObject parent = nullptr) : QTcpServer(parent) {
connect(this, &QTcpServer::newConnection, this, &MyServer::handleNewConnection);