简体   繁体   中英

Qt TCP/IP communication only works locally, but gets lost in a network

I've created two simple TCP/IP communication programs (server & client). It basically just sends and receives the same message over and over again.

However when I execute client and server on the same workstation everything runs fine. It is only then, when I execute the same programs via a lokal network that the server doesn't receive any incomming connection requests.

The firewall is disabled on both stations. Has anyone an idea what I'm missing out?

Here is the code


client.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");
}

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);
}

I'm first initiating the server program following by the client

You need to use the remote machine's IP address to connect. Now you are always connecting to 127.0.0.1, which is the machine where the application is being run. That is why the connection is never made to a remote machine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM