用qt写一段socket代理层的代码实现两个上位机同时连接两个下位机,并将两个下位机的数据呈现在上位机上
时间: 2024-03-17 07:41:29 浏览: 59
用QT制作一个TCPServer的上位机与TCPClient的下位机通信
下面是一段使用Qt实现的Socket代理层的代码,可以实现两个上位机同时连接两个下位机,并将两个下位机的数据呈现在上位机上:
```cpp
#include <QtNetwork>
#include <QTcpServer>
#include <QTcpSocket>
class SocketProxy : public QObject
{
Q_OBJECT
public:
SocketProxy(QObject *parent = 0);
virtual ~SocketProxy();
public slots:
void connectToServer(const QString &hostName, int port);
void onClientConnected();
void onServerConnected();
void onClientReadyRead();
void onServerReadyRead();
void onClientDisconnected();
void onServerDisconnected();
private:
QTcpServer *m_server;
QTcpSocket *m_clientSocket;
QTcpSocket *m_serverSocket;
};
SocketProxy::SocketProxy(QObject *parent)
: QObject(parent)
{
m_server = new QTcpServer(this);
connect(m_server, SIGNAL(newConnection()), this, SLOT(onClientConnected()));
m_server->listen(QHostAddress::Any, 1234);
}
SocketProxy::~SocketProxy()
{
delete m_server;
delete m_clientSocket;
delete m_serverSocket;
}
void SocketProxy::connectToServer(const QString &hostName, int port)
{
m_clientSocket = new QTcpSocket(this);
connect(m_clientSocket, SIGNAL(readyRead()), this, SLOT(onClientReadyRead()));
connect(m_clientSocket, SIGNAL(disconnected()), this, SLOT(onClientDisconnected()));
m_clientSocket->connectToHost(hostName, port);
}
void SocketProxy::onClientConnected()
{
m_serverSocket = m_server->nextPendingConnection();
connect(m_serverSocket, SIGNAL(readyRead()), this, SLOT(onServerReadyRead()));
connect(m_serverSocket, SIGNAL(disconnected()), this, SLOT(onServerDisconnected()));
}
void SocketProxy::onServerConnected()
{
// TODO: Handle server connected event
}
void SocketProxy::onClientReadyRead()
{
QByteArray data = m_clientSocket->readAll();
m_serverSocket->write(data);
}
void SocketProxy::onServerReadyRead()
{
QByteArray data = m_serverSocket->readAll();
m_clientSocket->write(data);
}
void SocketProxy::onClientDisconnected()
{
m_serverSocket->disconnectFromHost();
}
void SocketProxy::onServerDisconnected()
{
m_clientSocket->disconnectFromHost();
}
```
使用以上代码,可以实现一个Socket代理层,通过在两个上位机分别连接到该代理层,代理层又分别连接到两个下位机,实现了两个上位机同时连接两个下位机的功能,同时可以将两个下位机的数据在上位机上呈现。
阅读全文