QT实现服务端与客户端通信的例子
时间: 2023-02-24 09:50:17 浏览: 154
QT是一个功能强大的跨平台应用程序框架,支持许多编程语言,其中包括C++。下面是使用QT实现服务端和客户端通信的示例代码:
服务端代码:
```
#include <QtNetwork>
#include <QTextStream>
#include <QDebug>
int main()
{
QTcpServer server;
server.listen(QHostAddress::Any, 1234);
qDebug() << "Server started";
while (true) {
while (server.waitForNewConnection(1000)) {
qDebug() << "New client connected";
QTcpSocket *socket = server.nextPendingConnection();
QTextStream stream(socket);
stream << "Hello, client!" << endl;
socket->flush();
socket->waitForBytesWritten(1000);
socket->close();
qDebug() << "Closed connection";
}
}
return 0;
}
```
客户端代码:
```
#include <QtNetwork>
#include <QTextStream>
#include <QDebug>
int main()
{
QTcpSocket socket;
socket.connectToHost("localhost", 1234);
qDebug() << "Connecting to server";
socket.waitForConnected(1000);
qDebug() << "Connected to server";
QTextStream stream(&socket);
QString message;
stream >> message;
qDebug() << "Received from server:" << message;
socket.close();
qDebug() << "Closed connection";
return 0;
}
```
这是一个简单的示例,仅用于演示QT的通信功能。你可以根据需要修改代码以实现更复杂的通信。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)