qudp socket信号不触发_QT QUdpSocket的连接判断以及错误显示

本文介绍了在QT中使用QUdpSocket进行连接的两种方式,并展示了如何监听和处理连接状态改变、错误信息的显示。通过connectToHost()函数连接到指定的主机和端口,并设置信号槽来响应连接成功、失败或断开的事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 & hostName, quint16 port, OpenMode openMode =

ReadWrite )

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

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

2.void QAbstractSocket::connectToHost (

const QHostAddress & address, quint16 port, OpenMode 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

#include

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()<

}

void MainWindow::hasconnected()

{

qDebug()<

}

void MainWindow::hasnotconnected()

{

qDebug()<

}

void MainWindow::pushButton_clicked()

{   QString string=ui->lineEdit->text();

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

}

void MainWindow::erro()

{

qDebug()<

QString string=udpSocket->errorString();//此处为错误打印

qDebug()<

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值