QT 네트워크 프로 그래 밍 UDP 에서 C/S 구조 방송 통신(인 스 턴 스 설명)
먼저 서버 를 만 듭 시다.하위 클래스 를 쓰 고 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 구조 방송 통신(인 스 턴 스 설명)은 바로 편집장 이 여러분 에 게 공유 한 모든 내용 입 니 다.여러분 께 참고 가 되 고 저희 도 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Java Socket 프로그래밍 인스턴스(2) - UDP 기본 사용하나.서버 코드: 2.클라이언트 코드: 상기 코드의 UDP 서버는 단일 라인으로 클라이언트를 한 번에 한 번만 서비스할 수 있습니다. 다음은 본문의 전체 내용입니다. 더 많은 Java 문법을 보십시오.《 》、《 》、...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.