Qt是一个强大的跨平台C 框架,提供了丰富的网络编程功能。下面是一个简单的Qt网络编程实例,演示了如何使用Qt的网络模块进行客户端和服务器端的通信。
```cpp
include
include
include
class Server : public QTcpServer {
Q_OBJECT
public:
Server(QObject* parent = nullptr) : QTcpServer(parent) {
listen(QHostAddress::Any, 1234); // 监听1234端口
}
protected:
void incomingConnection(qintptr socketDescriptor) override {
QTcpSocket* socket = new QTcpSocket(this);
socket>setSocketDescriptor(socketDescriptor);
connect(socket, &QTcpSocket::readyRead, this, [=]() {
QByteArray data = socket>readAll();
qDebug() << "Received: " << data;
});
connect(socket, &QTcpSocket::disconnected, this, [=]() {
qDebug() << "Client disconnected";
socket>deleteLater();
});
}
};
int main(int argc, char* argv[]) {
QCoreApplication app(argc, argv);
Server server;
return app.exec();
}
include "main.moc"
```
```cpp
include
include
int main(int argc, char* argv[]) {
QCoreApplication app(argc, argv);
QTcpSocket socket;
socket.connectToHost("127.0.0.1", 1234); // 连接到服务器
if (socket.waitForConnected()) {
qDebug() << "Connected to server";
socket.write("Hello from client");
socket.waitForBytesWritten();
socket.disconnectFromHost();
} else {
qDebug() << "Connection failed";
}
return app.exec();
}
```
以上代码实现了一个简单的TCP客户端服务器端通信。服务器端监听1234端口,客户端连接到服务器后发送消息,服务器端接收消息并打印到控制台。
在实际应用中,你可以根据需要对这个基本示例进行扩展,添加加密、认证、错误处理等功能,以满足你的具体需求。
文章已关闭评论!
2024-11-26 17:47:52
2024-11-26 17:46:44
2024-11-26 17:45:24
2024-11-26 17:44:15
2024-11-26 17:43:01
2024-11-26 17:41:56
2024-11-26 17:40:33
2024-11-26 17:39:19