Qt无法连接到服务器
问题描述:
我想创建一个简单的服务器,只有当有人连接到我时才会显示。一切正常时,客户端和服务器使用“localhost”作为主机名进行连接,但是当我改变localhost来我的IP地址,然后我得到超时错误:( 有我的代码:Qt无法连接到服务器
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
server_status=0;
}
void MainWindow::on_starting_clicked()
{
tcpServer = new QTcpServer(this);
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newuser()));
if (!tcpServer->listen(QHostAddress::Any, 33333) && server_status==0) {
qDebug() << QObject::tr("Unable to start the server: %1.").arg(tcpServer->errorString());
ui->textinfo->append(tcpServer->errorString());
} else {
server_status=1;
qDebug() << tcpServer->isListening() << "TCPSocket listen on port";
ui->textinfo->append(QString::fromUtf8("Server started!"));
qDebug() << QString::fromUtf8("Server started!");
}
}
void MainWindow::on_stoping_clicked()
{
if(server_status==1){
foreach(int i,SClients.keys()){
QTextStream os(SClients[i]);
os.setAutoDetectUnicode(true);
os << QDateTime::currentDateTime().toString() << "\n";
SClients[i]->close();
SClients.remove(i);
}
tcpServer->close();
ui->textinfo->append(QString::fromUtf8("Server stopped!"));
qDebug() << QString::fromUtf8("Server stopped!");
server_status=0;
}
}
void MainWindow::newuser()
{
if(server_status==1){
qDebug() << QString::fromUtf8("New connection!");
ui->textinfo->append(QString::fromUtf8("New connection!"));
QTcpSocket* clientSocket=tcpServer->nextPendingConnection();
int idusersocs=clientSocket->socketDescriptor();
SClients[idusersocs]=clientSocket;
connect(SClients[idusersocs],SIGNAL(readyRead()),this, SLOT(slotReadClient()));
}
}
而对于客户端:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
socket = new QTcpSocket(this);
socket->connectToHost("95.220.162.117", 33333);
socket->waitForConnected();
}
MainWindow::~MainWindow()
{
delete ui;
}
我与网络工作领域的新手,所以请给我解释一下我在做什么错
答
“95.220.162.117”看起来像一个公共欧洲IP地址,该公共IP地址。由您的所有电脑/平板电脑/电话/等共享home家/办公室。这样想:公共IP地址指向您的路由器,而不是指向特定的计算机。
当客户端向公有IP地址发送请求时,路由器首先收到请求。然后,路由器的工作就是将请求转发到正确的设备......但在您的情况下,您的路由器不知道哪个设备应该接收请求!
有两个级别使您的连接工作:
1.私营:在你的本地网络(容易)
在你的服务器上,打开您的控制台,然后输入以下找到你的私人/本地IP地址:
ifconfig -a
您的本地IP地址与您的公共IP地址不同。它标识本地网络上的特定计算机。让你的客户端连接到这个地址,你的服务器应该收到请求。
这仅适用于在客户端和服务器在同一本地网络(例如连接到同一个路由器)
2.公共上:通过互联网(硬)
您需要设置Port Forwarding - 这会告诉路由器在端口33333接收请求并将它们转发到您的服务器。
要了解关于此主题的更多信息,请阅读Network Address Translation。
听起来像防火墙阻止了你。服务器的操作系统是什么? – 2014-11-04 23:15:26
OSX 10.9和防火墙关闭 – Lobster 2014-11-04 23:41:24
使用本地主机连接防火墙规则时,通常允许所有事情都通过自己。当从外部网络接口连接时 - 防火墙规则有助于防止入侵。端口33333是您必须在防火墙设置中取消阻止的端口。这[Apple如何](http://support.apple.com/en-us/ht1810)可能会帮助您打开使用的端口。 – 2014-11-04 23:44:38