利用QT的UDP技術,實現兩個QT程序之間的聊天程序。
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QUdpSocket> #include <QPushButton> #include <QLineEdit> #include <QTextBrowser> #include <QLabel> #include <QCloseEvent> class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); private: QUdpSocket *udpsock; QPushButton *btn1,*btn2,*btn3; QLineEdit *edit1,*edit2,*edit3; QLabel *label1,*label2,*label3; QTextBrowser *text1; void closeEvent(QCloseEvent *event); private slots: void mybindip(); void mysenddata(); void recvmydata(); }; #endif // WIDGET_H
#include "widget.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <QHostAddress> #include <QMessageBox> Widget::Widget(QWidget *parent) : QWidget(parent) { this->setWindowTitle("聊天室"); udpsock=new QUdpSocket(this); //udpsock->bind(8080); connect(udpsock,SIGNAL(readyRead()),this,SLOT(recvmydata())); label1=new QLabel(tr("發送端口號:")); edit1=new QLineEdit(); label2=new QLabel(tr("接收端口號:")); edit2=new QLineEdit(); btn1=new QPushButton(tr("綁定")); connect(btn1,SIGNAL(clicked()),this,SLOT(mybindip())); btn2=new QPushButton(tr("發送")); connect(btn2,SIGNAL(clicked()),this,SLOT(mysenddata())); label3=new QLabel(tr("消息內容:")); edit3=new QLineEdit(); text1=new QTextBrowser(); QHBoxLayout *lay1=new QHBoxLayout(); lay1->addWidget(label1); lay1->addWidget(edit1); lay1->addWidget(label2); lay1->addWidget(edit2); lay1->addWidget(btn1); QHBoxLayout *lay2=new QHBoxLayout(); lay2->addWidget(label3); lay2->addWidget(edit3); lay2->addWidget(btn2); QVBoxLayout *lay3=new QVBoxLayout(this); lay3->addLayout(lay1); lay3->addLayout(lay2); lay3->addWidget(text1); } //綁定接收端口號 void Widget::mybindip() { udpsock->close(); //獲取接收端口號 QString port1=edit2->text(); if(port1.isEmpty()) { QMessageBox::critical(this,"錯誤信息","發送端口號不能夠爲空!"); return ; } udpsock->bind(port1.toInt()); QMessageBox::information(this,"提示信息","綁定成功!端口號是"+port1); } //發送消息 void Widget::mysenddata() { //獲取發送端口號 QString port2=edit1->text(); if(port2.isEmpty()) { QMessageBox::critical(this,"錯誤信息","發送端口號不能夠爲空!"); return ; } //獲取發送內容 QString txt=edit3->text(); char buf[1024]={0}; strcpy(buf,txt.toStdString().data()); //定義地址類 QHostAddress *serip=new QHostAddress(); serip->setAddress("127.0.0.1"); udpsock->writeDatagram(buf,strlen(buf),*serip,port2.toInt()); delete serip; edit3->clear(); edit3->setFocus(); } //接收消息 void Widget::recvmydata() { QMessageBox::information(this,"提示信息","接收到消息"); char buf[1024]={0}; while(udpsock->hasPendingDatagrams()) { udpsock->readDatagram(buf,sizeof(buf)); text1->append(buf); memset(buf,0,sizeof(buf)); } } //關閉 void Widget::closeEvent(QCloseEvent *event) { if(QMessageBox::information(this,"提示信息","肯定要退出該程序?",QMessageBox::Yes|QMessageBox::No,QMessageBox::No)==QMessageBox::Yes) { event->accept(); }else { event->ignore(); } } Widget::~Widget() { }