用qt写一段代码通过socket实现三台上位机都能对下位机进行控制,但不是同时控制。 同一时刻只能有一台在控制,但三台能同时读下位机的数据功能
时间: 2024-01-21 14:15:53 浏览: 58
以下是一个基本的代码示例,实现了三个上位机通过 socket 连接到下位机,并可以控制和读取数据。在此示例中,只有一个上位机可以控制下位机,其他两个上位机只能读取下位机的数据。您可以根据自己的需求进行修改。
```cpp
// server.cpp
#include <QtNetwork>
#include <QTcpServer>
#include <QTcpSocket>
QTcpServer *server;
QTcpSocket *socket1;
QTcpSocket *socket2;
QTcpSocket *socket3;
void readSocketData()
{
QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
QByteArray data = socket->readAll();
// 处理读取到的数据
}
void acceptConnection()
{
QTcpSocket *socket = server->nextPendingConnection();
if (!socket1) {
socket1 = socket;
QObject::connect(socket1, SIGNAL(readyRead()), readSocketData);
QObject::connect(socket1, SIGNAL(disconnected()), socket1, SLOT(deleteLater()));
socket1->write("You are controlling the device.\n");
} else if (!socket2) {
socket2 = socket;
QObject::connect(socket2, SIGNAL(readyRead()), readSocketData);
QObject::connect(socket2, SIGNAL(disconnected()), socket2, SLOT(deleteLater()));
socket2->write("You can only read data from the device.\n");
} else if (!socket3) {
socket3 = socket;
QObject::connect(socket3, SIGNAL(readyRead()), readSocketData);
QObject::connect(socket3, SIGNAL(disconnected()), socket3, SLOT(deleteLater()));
socket3->write("You can only read data from the device.\n");
} else {
socket->write("The device is currently being controlled.\n");
socket->close();
socket->deleteLater();
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
server = new QTcpServer();
QObject::connect(server, SIGNAL(newConnection()), acceptConnection);
if (!server->listen(QHostAddress::Any, 1234)) {
qDebug() << "Failed to start server.";
return 1;
}
qDebug() << "Server started.";
return app.exec();
}
```
```cpp
// client.cpp
#include <QtNetwork>
#include <QTcpSocket>
QTcpSocket *socket;
void readSocketData()
{
QByteArray data = socket->readAll();
// 处理读取到的数据
}
void connectToServer()
{
socket = new QTcpSocket();
QObject::connect(socket, SIGNAL(readyRead()), readSocketData);
QObject::connect(socket, SIGNAL(disconnected()), qApp, SLOT(quit()));
socket->connectToHost("localhost", 1234);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
connectToServer();
return app.exec();
}
```
阅读全文