Qt网络应用----socket通信例子
Gui Application,工程名为“udpone”,work模块,Base class选择QMainWindow。(说明:如果一些Qt Creator版本没有添加模块一项,:QT += network)
(Text Edit),左边的那个的objectName改为为textSend,右边的那个的objectName改为textReceive,添加一个按钮,改其objectName为send,如下所示:
#include <work>,
添加public变量 QHostAddress *hostaddr1;和 QHostAddress *hostaddr2;
添加private变量 QUdpSocket *udpSocket1;和QUdpSocket *udpSocket2;
添加私有槽函数:
private slots:
void send();
void receive();
,加入如下代码:
(1)在构造函数中添加:
udpSocket1=new QUdpSocket(this);
udpSocket2=new QUdpSocket(this);
hostaddr1 = new QHostAddress("");
hostaddr2 = new QHostAddress("");
bool conn=udpSocket1->bind(*hostaddr1,6666,QUdpSocket::ShareAddress);//监听本机上的6666端口,如果有消息到来,就会发送readyRead()信号。
if(!conn){
QMessageBox box;
(tr("连接错误"));
();
}else{
connect(udpSocket1,SIGNAL(readyRead()),this,SLOT(receive()));
connect(ui->send,SIGNAL(clicked()),this,SLOT(send()));
}
(2)实现send函数:
void MainWindow::send()
{
QMessageBox box;
QString text=ui->textSend->toPlainText();
if(()==0){
(tr("请输入发送内容"));
();
}
udpSocket2->writeDatagram((),(),*hostaddr
Qt网络应用----socket通信例子 来自淘豆网www.taodocs.com转载请标明出处.