编写了简单的客户端和服务器程序。使用本地连接一切正常。一旦您将客户端指向socket->connectToHost(...);您的全局 IP 地址,套接字就会显示错误“连接被拒绝”。。服务器正在监听QHostAddress::Any。尝试通过本地 IP 和全球 IP 进行连接时有什么区别吗?我使用QTcpServer套接字作为服务器QTcpSocket。 IP地址是白色的。
更新:
当客户端从另一台机器连接到另一台路由器时,显示“网络操作超时”
服务器.cpp
Server::Server()
{
if(listen(QHostAddress::Any, 1234)) {
qDebug() << "start";
}
else {
qDebug() << "ne start";
}
}
处理客户端连接:
void Server::incomingConnection(qintptr handle)
{
socket = new QTcpSocket;
socket->setSocketDescriptor(handle);
connect(socket, &QTcpSocket::readyRead, this, &Server::slotReadyRead);
connect(socket, &QTcpSocket::disconnected, this, &Server::socketDisconnected);
sockets.push_back(socket);
qDebug() << "client connected" << handle;
}
客户端.cpp
将套接字连接到服务器
Widget::Widget(QWidget *parent)
: QWidget(parent),
socket(new QTcpSocket(this))
{
connect(socket, &QTcpSocket::readyRead, this, &Widget::slotReadyRead);
connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
connect(socket, &QTcpSocket::errorOccurred, this, &Widget::socketError);
socket->connectToHost("178.65.126.214", 1234);
socket->waitForConnected();
}

感谢评论中的提示,我在路由器菜单中配置了端口转发,从所需的端口到所需的本地 IP,一切正常。在我的路由器上它看起来像这样: