QT 네트워크 프로 그래 밍 UDP 에서 C/S 구조 방송 통신(인 스 턴 스 설명)

QT 에는 봉 인 된 UDP 프로 토 콜 의 클래스 가 있 습 니 다.QUdpSocket 에는 우리 가 원 하 는 함수 인터페이스 가 있 습 니 다.관심 있 으 면 보 세 요.
먼저 서버 를 만 듭 시다.하위 클래스 를 쓰 고 QDialog 클래스 를 계승 하여 UdpServer 클래스 로 이름 을 지 었 습 니 다.헤더 파일 은 위 에서 말 한 QUdpSocket 클래스 와 우리 가 원 하 는 레이아웃 클래스 를 참조 해 야 합 니 다.

#ifndef UDPSERVER_H
#define UDPSERVER_H

#include <QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QtNetwork/QUdpSocket>
#include <QtNetwork/QHostAddress>
#include <QTimer>
class UdpServer : public QDialog
{
 Q_OBJECT
public:
 UdpServer(QWidget *parent = 0,Qt::WindowFlags f= 0);
 ~UdpServer();
private:
 QLabel * TimerLabel;
 QLineEdit * TextLineEdit;
 QPushButton* StartBtn;
 QVBoxLayout * mainLayout;
 public slots:
 void StartBtnClicked();
 void timeout();
 private:
 int port;
 bool isStarted;
 QUdpSocket * udpSocket;
 QTimer *timer;
};
#endif // UDPSERVER_H
.cpp 파일 에서,우 리 는 먼저 인 터 페 이 스 를 표시 한 다음,udp 의 writedategram 으로 전하 고 싶 은 것 을 쓴다.

#include "udpserver.h"


UdpServer::UdpServer(QWidget *parent,Qt::WindowFlags f)
 : QDialog(parent,f)
{
 setWindowTitle(tr("UDP SERVER"));
 TimerLabel = new QLabel(tr("show time:"),this);
 TextLineEdit = new QLineEdit(this);
 StartBtn = new QPushButton(tr("start"),this);

 mainLayout = new QVBoxLayout(this);
 mainLayout-> addWidget(TimerLabel);
 mainLayout-> addWidget(TextLineEdit);
 mainLayout-> addWidget(StartBtn);

 connect(StartBtn,SIGNAL(clicked()),this,SLOT(StartBtnClicked()));
 port = 5555;
 isStarted = false;
 udpSocket = new QUdpSocket(this);
 timer = new QTimer(this);
 connect(timer,SIGNAL(timeout()),this,SLOT(timeout()));

}

UdpServer::~UdpServer()
{

}
void UdpServer::StartBtnClicked()
{
 if(!isStarted)
 {
  StartBtn->setText(tr("STOP"));
  timer->start(1000);
  isStarted = true;
 }
 else
 {
  StartBtn->setText(tr("BEGIN"));
  isStarted = false;
  timer->stop();
 }
}
void UdpServer::timeout()
{
 QString msg = TextLineEdit->text();
 int length=0;
 if(msg=="")
 {
  return;
 }

 if((length=udpSocket->writeDatagram(msg.toLatin1(),msg.length(),QHostAddress::Broadcast,port))!=msg.length())
 {
  qDebug() << msg.toLatin1();
  return;
 }
}
전 할 물건 을 qDebug 로 인쇄 해서 전 달 했 는 지 확인 해 보 겠 습 니 다.
클 라 이언 트:

#ifndef UDPCLIENT_H
#define UDPCLIENT_H
#include <QDialog>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QPushButton>
#include <QtNetwork/QUdpSocket>
 class UdpClient : public QDialog
{
 Q_OBJECT
 public:
 UdpClient(QWidget *parent = 0);
 ~UdpClient();
 private:
 QTextEdit* ReceiceTextEdit;
 QPushButton* CloseBtn;
 QVBoxLayout* mainLayout;
 public slots:
 void CloseBtnClicked();
 void dataReceived();
 private:
 int port;
 QUdpSocket* udpSocket;
};
#endif // UDPCLIENT_H
클 라 이언 트 는 매우 간단 합 니 다.레이아웃 을 어떻게 실현 하 는 지 저 는 더 이상 말 하지 않 겠 습 니 다.주로 dataReceive 함수 입 니 다.

#include "udpclient.h"
#include <QMessageBox>
#include <QHostAddress>


UdpClient::UdpClient(QWidget *parent)
 :QDialog(parent)
{
 setWindowTitle("UDP CLIENT");

 ReceiceTextEdit = new QTextEdit(this);
 CloseBtn = new QPushButton(tr("Close"),this);

 mainLayout = new QVBoxLayout(this);
 mainLayout->addWidget(ReceiceTextEdit);
 mainLayout->addWidget(CloseBtn);

 connect(CloseBtn,SIGNAL(clicked()),this,SLOT(CloseBtnClicked()));

 port =5555;

 udpSocket = new QUdpSocket(this);

 bool result = udpSocket->bind(port);

 if(!result)
 {
  QMessageBox::information(this,tr("ERROR"),tr("connect error"));
  return;
 }
 connect(udpSocket,SIGNAL(readyRead()),this,SLOT(dataReceived()));

}
 UdpClient:: ~UdpClient()
{


}
void UdpClient::CloseBtnClicked()
{
 close();
}
void UdpClient::dataReceived()
{
 while(udpSocket->hasPendingDatagrams())
 {

  QByteArray datagram;
  datagram.resize(udpSocket->pendingDatagramSize());
  udpSocket->readDatagram(datagram.data(),datagram.size());
  QString msg=datagram.data();
  ReceiceTextEdit->insertPlainText(msg);

 }
}
마지막 으로 인터페이스 를 표시 하고 서버 에서 hello 를 보 냅 니 다.

클 라 이언 트 가 받 은:

끊임없이 hello 를 인쇄 하고 있 습 니 다.닫 기 를 누 르 거나 서버 가 멈 출 때 까지.
이상 의 이 QT 네트워크 프로 그래 밍 UDP 에서 C/S 구조 방송 통신(인 스 턴 스 설명)은 바로 편집장 이 여러분 에 게 공유 한 모든 내용 입 니 다.여러분 께 참고 가 되 고 저희 도 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기