gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:11:24 26 4
gpt4 key购买 nike

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

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

防火墙在两个站点上都被禁用。有人知道我错过了什么吗?

这是代码


客户端.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);
}

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

最佳答案

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

关于c++ - Qt TCP/IP 通信只能在本地工作,但在网络中会丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35553597/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com