我想創建一個簡單的服務器,只有當有人連接到我時纔會顯示。一切正常時,客戶端和服務器使用「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;
}
我與網絡工作領域的新手,所以請給我解釋一下我在做什麼錯
聽起來像防火牆阻止了你。服務器的操作系統是什麼? – 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