源码:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QHostAddress>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
udpSocket=new QUdpSocket();
//QHostAddress *hostaddr;
//hostaddr= new QHostAddress("211.87.147.238");//主机IP
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(pushButton_clicked()));
connect(udpSocket,SIGNAL(hostFound()),this,SLOT(hasfindhost()));
connect(udpSocket,SIGNAL(connected()),this,SLOT(hasconnected()));
connect(udpSocket,SIGNAL(disconnected()),this,SLOT(hasnotconnected()));
connect(udpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(erro()));
}
//QHostAddress::LocalHost
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::hasfindhost()
{
qDebug()<<"HAS FOND HOST";
}
void MainWindow::hasconnected()
{
qDebug()<<"has connected";
}
void MainWindow::hasnotconnected()
{
qDebug()<<"has not connected";
}
void MainWindow::pushButton_clicked()
{ QString string=ui->lineEdit->text();
udpSocket->connectToHost(string,6666,QIODevice::ReadWrite);
}
void MainWindow::erro()
{
qDebug()<<"AN erro";
QString string=udpSocket->errorString();
qDebug()<<string;
}
运行:
如果开始网线连接,则
HAS FOND HOST
has connected
断开网线,再点击按钮就出现:
QAbstractSocket::connectToHost() called when already looking up or connecting/connected to "211.87.147.238"
QAbstractSocket::connectToHost() called when already looking up or connecting/connected to "211.87.147.238"
如果刚开始断开网线,则:
AN erro
"Host not found"
连上网线,再点击按钮就出现:
HAS FOND HOST
has connected
QAbstractSocket::connectToHost() called when already looking up or connecting/connected to "211.87.147.238"
为什么void MainWindow::hasnotconnected()和void MainWindow::erro()不执行呢??
是不是 udpSocket->connectToHost(string,6666,QIODevice::ReadWrite);以后要复位一下,怎么复位??
udpSocket 通讯中你怎样实时判断他是否连接上和断开?
------解决方案--------------------
QNetworkConfigurationManager::isOnline()
UDP根本不在乎发包是否成功,只要从传输层发出去就算是完成任务了