Qt TCP/IP通信只能在本地工作,但在网络中会丢失
Qt TCP/IP communication only works locally, but gets lost in a network
我创建了两个简单的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,这是运行应用程序的计算机。这就是为什么永远不会连接到远程计算机的原因。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 通过网络、跨平台传递std::变体是否安全
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 对等如何实际工作网络/端口明智
- Qt TCP/IP通信只能在本地工作,但在网络中会丢失
- 在Windows中C++开发一个P2P网络项目,该项目应该在Linux中工作
- 来自 boost::asio::async_write 的 WriteHandler 在连接断开时无法正常工作(防火墙/手动断开网络)
- 猫鼬网络服务器获取当前工作线程
- 数字识别,神经网络工作不正常
- 不能让简单的boost网络示例工作,仅仅初始化服务器立即导致错误
- 神经网络似乎工作得很好,直到用于处理数据(所有的结果几乎是相同的)
- TCP聊天不能在不同的网络中工作
- 让网络摄像头在OpenCV中工作