使用QT的QTcpSocket与QTcpServer类实现简单Tcp通讯
时间: 2023-04-09 20:04:21 浏览: 105
可以使用QT的QTcpSocket与QTcpServer类来实现简单的Tcp通讯。以下是一个简单的示例代码:
// 服务器端代码
QTcpServer *server = new QTcpServer(this);
if (!server->listen(QHostAddress::Any, 1234)) {
qDebug() << "Server could not start!";
} else {
qDebug() << "Server started!";
}
connect(server, &QTcpServer::newConnection, [=]() {
QTcpSocket *socket = server->nextPendingConnection();
qDebug() << "New client connected:" << socket->peerAddress().toString();
connect(socket, &QTcpSocket::readyRead, [=]() {
QByteArray data = socket->readAll();
qDebug() << "Received data:" << data;
});
connect(socket, &QTcpSocket::disconnected, [=]() {
qDebug() << "Client disconnected:" << socket->peerAddress().toString();
});
});
// 客户端代码
QTcpSocket *socket = new QTcpSocket(this);
socket->connectToHost("127.0.0.1", 1234);
if (socket->waitForConnected()) {
qDebug() << "Connected to server!";
socket->write("Hello server!");
} else {
qDebug() << "Failed to connect to server!";
}
connect(socket, &QTcpSocket::readyRead, [=]() {
QByteArray data = socket->readAll();
qDebug() << "Received data:" << data;
});
connect(socket, &QTcpSocket::disconnected, [=]() {
qDebug() << "Disconnected from server!";
});
注意:以上代码仅为示例,实际使用时需要根据具体需求进行修改。
阅读全文