简体   繁体   English

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

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

I've created two simple TCP/IP communication programs (server & client). 我创建了两个简单的TCP / IP通信程序(服务器和客户端)。 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. 直到那时,当我通过lokal网络执行相同的程序时,服务器才没有收到任何传入的连接请求。

The firewall is disabled on both stations. 在两个工作站上都​​禁用了防火墙。 Has anyone an idea what I'm missing out? 有谁知道我错过了什么?

Here is the code 这是代码


client.cpp 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 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. 您需要使用远程计算机的IP地址进行连接。 Now you are always connecting to 127.0.0.1, which is the machine where the application is being run. 现在,您始终连接到127.0.0.1,这是运行应用程序的计算机。 That is why the connection is never made to a remote machine. 这就是为什么从不连接到远程计算机的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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