Qt中实现域(Unix)套接字通信可以使用QLocalServer和QLocalSocket类。以下是一个简单的示例,演示了如何在两个Qt应用程序之间使用域套接字进行通信。
一、在服务器端:
cpp
Copy code
#include <QtWidgets>
#include <QLocalServer>
#include <QLocalSocket>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QLocalServer server;
if (!server.listen("myserver")) {
qDebug() << "Error: " << server.errorString();
return 1;
}
qDebug() << "Server listening...";
QObject::connect(&server, &QLocalServer::newConnection, [&](){
QLocalSocket *socket = server.nextPendingConnection();
if (!socket) {
return;
}
QObject::connect(socket, &QLocalSocket::readyRead, [&](){
QByteArray data = socket->readAll();
qDebug() << "Received: " << data;
socket->write("Message received.");
});
});
return app.exec();
}
二、 在客户端:
cpp
Copy code
#include <QtWidgets>
#include <QLocalSocket>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QLocalSocket socket;
socket.connectToServer("myserver");
if (!socket.waitForConnected()) {
qDebug() << "Error: " << socket.errorString();
return 1;
}
qDebug() << "Connected to server.";
socket.write("Hello from client.");
if (!socket.waitForBytesWritten()) {
qDebug() << "Error writing to server: " << socket.errorString();
return 1;
}
if (!socket.waitForReadyRead()) {
qDebug() << "Error reading from server: " << socket.errorString();
return 1;
}
QByteArray response = socket.readAll();
qDebug() << "Server response: " << response;
return app.exec();
}
这是一个简单的示例,说明了如何使用QLocalServer和QLocalSocket在Qt应用程序之间进行域套接字通信。在实际应用中,您可能需要更复杂的逻辑来处理连接、数据传输和错误处理