Qt TCP/IP通信只能在本地工作,但在网络中会丢失



我创建了两个简单的TCP/IP通信程序(服务器和客户端)。它基本上只是一遍又一遍地发送和接收相同的消息。

但是,当我在同一工作站上执行客户端服务器时,一切运行良好。只有这样,当我通过 lokal 网络执行相同的程序时,服务器才不会收到任何传入的连接请求。

两个工作站上的防火墙均已禁用。有人知道我错过了什么吗?

这是代码


客户端.cpp

#include "client.h"
#include <QHostAddress>
#include <iostream>
#include <conio.h>
Client::Client(QObject* parent): QObject(parent)
{
connect(&client, SIGNAL(connected()), this, SLOT(startTransfer()));
connect(&client, SIGNAL(readyRead()), this, SLOT(receive()));
QHostAddress addr = QHostAddress("127.0.0.1");
client.connectToHost(addr, 5200);
}
Client::~Client()
{
client.close();
}
void Client::startTransfer()
{
client.write("Hello, world", 13);
send("start client communication");
}
void Client::send(const char *buffer)
{
    std::cout<<"OUT: "<<buffer<<std::endl;
    client.write(buffer,strlen(buffer));

}
void Client::receive()
{
    char temp[1024] = {0};
    int len = client.read(temp,client.bytesAvailable());
    std::cout<<"IN: "<< temp<<std::endl;
    send("client to server");
}

服务器.cpp

#include "theserver.h"
#include <iostream>
#include <conio.h>
using namespace std;
Server::Server(QObject* parent): QObject(parent)
{
connect(&server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
server.listen(QHostAddress::Any, 5200);
}
Server::~Server()
{
server.close();
}
void Server::acceptConnection()
{
    client = server.nextPendingConnection();
    if(client)
    {
        connect(client, SIGNAL(readyRead()), this, SLOT(receive()));
    }
}
void Server::startRead()
{
char buffer[1024] = {0};
client->read(buffer, client->bytesAvailable());
cout << "IN: "<<buffer << endl;
}
void Server::receive()
{
    char buffer[1024] = {0};
    client->read(buffer, client->bytesAvailable());
    cout << "IN: "<<buffer << endl;
}
void Server::sendData(const char* buffer)
{
    cout <<"OUT: "<<buffer<<endl;
    if(client)
        client->write(buffer);
}

我首先启动服务器程序,然后由客户端启动

您需要使用远程计算机的 IP 地址进行连接。现在,您始终连接到 127.0.0.1,这是运行应用程序的计算机。这就是为什么永远不会连接到远程计算机的原因。

最新更新