使用QtTcpSocket创建一个控制台服务端程序,监听其他程序的连接请求,并与器交互
时间: 2024-03-03 10:48:55 浏览: 23
好的,以下是一个简单的使用 QtTcpSocket 创建控制台服务端程序的示例代码:
```c++
#include <QtCore/QCoreApplication>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTcpServer server;
if (!server.listen(QHostAddress::Any, 1234)) {
qCritical() << "Failed to listen on port 1234";
return 1;
}
qDebug() << "Listening on port 1234";
QObject::connect(&server, &QTcpServer::newConnection, [&server]() {
QTcpSocket *socket = server.nextPendingConnection();
qDebug() << "Accepted new connection from" << socket->peerAddress().toString();
QObject::connect(socket, &QTcpSocket::readyRead, [socket]() {
QByteArray data = socket->readAll();
qDebug() << "Received data:" << data;
// TODO: process the data and send response back to the client
});
QObject::connect(socket, &QTcpSocket::disconnected, [socket]() {
qDebug() << "Connection closed by" << socket->peerAddress().toString();
socket->deleteLater();
});
});
return a.exec();
}
```
这个程序会监听端口 1234,并在有新的连接请求时接受连接。每当有数据到达时,会输出收到的数据并在需要时发送响应。注意要在 `TODO` 处添加实际的数据处理代码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)