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

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



评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值