分享

QT QUdpSocket的连接判断以及错误显示

 石头记143 2014-06-03

if you need a socket, you have two options:


1.Instantiate QTcpSocket or QUdpSocket //实例化

2.Create a native socket descriptor, instantiate QAbstractSocket, and call setSocketDescriptor() to wrap the native socket.

Internally 1.在内部,内存 internally 1.在内(部) 2.内部的

QUdpSocket的连接两种方式:


1.void QAbstractSocket::connectToHost ( const QString & hostNamequint16 portOpenMode openMode = ReadWrite )

例:udpSocket->connectToHost("211.87.147.238",6666,QIODevice::ReadWrite);

 或udpSocket->connectToHost("example.com",6666,QIODevice::ReadWrite);


2.void QAbstractSocket::connectToHost ( const QHostAddress & addressquint16 portOpenMode openMode = ReadWrite )

例:

QHostAddress *hostaddr;
hostaddr= new QHostAddress("211.87.147.238");//主机IP

udpSocket->connectToHost(*hostaddr,6666,QIODevice::ReadWrite);


连接源代码:

#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()));//先查看host是否存在
    connect(udpSocket,SIGNAL(connected()),this,SLOT(hasconnected()));//判断如果连接上
    connect(udpSocket,SIGNAL(disconnected()),this,SLOT(hasnotconnected()));//如果断开连接
   
connect(udpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(erro()));//显示错误
}

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;
}



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章