#include <QObject> #include <QTcpServer> #include <QTcpSocket> class TcpProxy : public QObject { Q_OBJECT public: explicit TcpProxy(QObject *parent = nullptr); signals: public slots: void onNewClientConnection(); void onClientDataReady(); void onServerDataReady(); private: QTcpServer *m_server; QTcpSocket *m_client1; QTcpSocket *m_client2; QTcpSocket *m_serverSocket; }; TcpProxy::TcpProxy(QObject *parent) : QObject(parent) { m_server = new QTcpServer(this); m_server->listen(QHostAddress::Any, 1234); connect(m_server, SIGNAL(newConnection()), this, SLOT(onNewClientConnection())); } void TcpProxy::onNewClientConnection() { if (!m_client1) { m_client1 = m_server->nextPendingConnection(); connect(m_client1, SIGNAL(readyRead()), this, SLOT(onClientDataReady())); qDebug() << "Client 1 connected"; } else if (!m_client2) { m_client2 = m_server->nextPendingConnection(); connect(m_client2, SIGNAL(readyRead()), this, SLOT(onClientDataReady())); qDebug() << "Client 2 connected"; } if (m_client1 && m_client2 && !m_serverSocket) { m_serverSocket = new QTcpSocket(this); connect(m_serverSocket, SIGNAL(readyRead()), this, SLOT(onServerDataReady())); m_serverSocket->connectToHost("localhost", 4321); // replace with your down-level machine's IP address and port number qDebug() << "Server connected"; } } void TcpProxy::onClientDataReady() { QTcpSocket *senderSocket = qobject_cast<QTcpSocket*>(sender()); QTcpSocket *destSocket = (senderSocket == m_client1) ? m_client2 : m_client1; QByteArray data = senderSocket->readAll(); destSocket->write(data); if (m_serverSocket) { m_serverSocket->write(data); } } void TcpProxy::onServerDataReady() { QByteArray data = m_serverSocket->readAll(); if (m_client1) { m_client1->write(data); } if (m_client2) { m_client2->write(data); } } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); TcpProxy tcpProxy; return a.exec(); }为什么两台电脑无法互通数据
时间: 2024-04-01 21:36:35 浏览: 134
Qt的tcp网络编程(客户端和服务器)
这段代码是一个 TCP 代理程序,主要实现了两个客户端与一个服务器的数据交互。如果两台电脑无法互通数据,可能是以下几个原因导致的:
1. 网络配置问题:确保两台电脑都处于同一个局域网内,并且 IP 地址和子网掩码设置正确。
2. 防火墙问题:确保防火墙没有阻止程序的网络通信。可以尝试关闭防火墙或添加程序的网络访问权限。
3. 端口号问题:确保代理程序监听的端口号(1234)和服务器连接的端口号(4321)都没有被其他程序占用。
如果以上问题都没有解决,还需要进一步排查程序代码是否存在问题。
阅读全文