【发布时间】:2014-11-04 23:10:59
【问题描述】:
我正在尝试创建一个简单的服务器,它只会在有人连接到我时显示。当客户端和服务器使用“localhost”作为主机名进行连接时,一切正常,但是当我将 localhost 更改为我的 IP 地址时,出现超时错误:( 有我的代码:
#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;
}
我是网络领域的新手,所以请解释一下我做错了什么
【问题讨论】:
-
听起来防火墙正在阻止您。服务器在什么操作系统上?
-
OSX 10.9 且防火墙已关闭
-
当使用 localhost 连接时,防火墙规则通常允许一切通过回到自身。从外部网络接口连接时 - 防火墙规则有助于防止入侵。端口 33333 是您必须在防火墙设置中取消阻止的端口。这个Apple how to可以帮你打开端口使用。
-
啊错过了“防火墙已关闭”哎呀。我刚看到 OS/X ;-) 。我假设您的意思是服务器上的防火墙已关闭?如果它位于公共互联网上,可能不是一个好主意