QT/C++——网络编程
创始人
2024-05-22 09:22:17
0

目录

一、基础知识复习

二、UDP

客户端:

服务器:

三、TCP

服务器:

客户端:

四、小项目

客户端:

服务器:


一、基础知识复习

这部分内容前面讲的比较详细,现在就是简单复习一下。

两台主机之间通信要经过封包他有一堆包头

 

TCP、UDP都是基于套接字,C写我感觉已经挺简单了,老师说C++更简单,我们往下学学看。

二、UDP

网络编程这块要在工程文件中加上network

服务器是被动套接字,客户端是主动套接字

客户端:

#ifndef WIDGET_H
#define WIDGET_H#include 
#include 
#include 
#include 
#include 
#include class Widget : public QWidget
{Q_OBJECT
public slots:void senddata(){udpsock->writeDatagram(le->text().toStdString().c_str(), QHostAddress("192.168.3.27"), 8888);}void recvdata(){QByteArray datagram;datagram.resize(udpsock->pendingDatagramSize());QHostAddress sender;quint16 senderPort;udpsock->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);te->append(datagram);}
public:Widget(QWidget *parent = 0);~Widget();
private:QTextEdit *te;QLineEdit *le;QPushButton *pb;QUdpSocket *udpsock;
};#endif // WIDGET_H
#include "widget.h"
#include Widget::Widget(QWidget *parent): QWidget(parent)
{te = new QTextEdit;le = new QLineEdit;pb = new QPushButton("send");QVBoxLayout *vbox = new QVBoxLayout;vbox->addWidget(te);vbox->addWidget(le);vbox->addWidget(pb);setLayout(vbox);udpsock = new QUdpSocket;connect(pb, SIGNAL(clicked(bool)), this, SLOT(senddata()));connect(udpsock, SIGNAL(readyRead()), this, SLOT(recvdata()));
}Widget::~Widget()
{}

服务器:

#ifndef UDPSERVER_H
#define UDPSERVER_H#include 
#include 
#include class udpServer : public QObject
{Q_OBJECT
public:explicit udpServer(QObject *parent = 0);void init(){udpSocket = new QUdpSocket(this);udpSocket->bind(QHostAddress::AnyIPv4, 8888);connect(udpSocket, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));qDebug()<<"init....";}
signals:public slots:void readPendingDatagrams(){while (udpSocket->hasPendingDatagrams()) {QByteArray datagram;datagram.resize(udpSocket->pendingDatagramSize());QHostAddress sender;quint16 senderPort;udpSocket->readDatagram(datagram.data(), datagram.size(),&sender, &senderPort);//processTheDatagram(datagram);qDebug()<<"recv: "<writeDatagram(datagram.data(), datagram.size(),sender, senderPort);}}private:QUdpSocket *udpSocket;
};#endif // UDPSERVER_H

两个程序的工程文件中一定要加入network

三、TCP

服务器:

#ifndef TCPSERVER_H
#define TCPSERVER_H#include 
#include 
#include 
#include class tcpServer : public QObject
{Q_OBJECT
public:explicit tcpServer(QObject *parent = 0);signals:public slots:void newconnected(){qDebug()<<"connected";clientsock = ser->nextPendingConnection();connect(clientsock, SIGNAL(readyRead()), this, SLOT(readdata()));}void readdata(){QByteArray buf =  clientsock->readAll();qDebug()<<"recv: "<write(buf);}private:QTcpServer *ser;QTcpSocket *clientsock;};#endif // TCPSERVER_H
#include "tcpserver.h"
#include tcpServer::tcpServer(QObject *parent) : QObject(parent)
{ser = new QTcpServer;ser->listen(QHostAddress::AnyIPv4, 8888);connect(ser, SIGNAL(newConnection()), this, SLOT(newconnected()));ser->waitForNewConnection();
}

客户端:

#ifndef WIDGET_H
#define WIDGET_H#include 
#include 
#include 
#include 
#include class Widget : public QWidget
{Q_OBJECT
public slots:void senddata(){tcpsocket->write(le->text().toStdString().c_str());}void recvdata(){QByteArray buf = tcpsocket->readAll();te->append(buf);}
public:Widget(QWidget *parent = 0);~Widget();
private:QTextEdit *te;QLineEdit *le;QPushButton *pb;QTcpSocket *tcpsocket;
};#endif // WIDGET_H
#include "widget.h"
#include 
#include Widget::Widget(QWidget *parent): QWidget(parent)
{te = new QTextEdit;le = new QLineEdit;pb = new QPushButton("send");QVBoxLayout *vbox = new QVBoxLayout;vbox->addWidget(te);vbox->addWidget(le);vbox->addWidget(pb);setLayout(vbox);tcpsocket = new QTcpSocket;//connect to servertcpsocket->connectToHost(QHostAddress("192.168.3.27"), 8888);connect(pb, SIGNAL(clicked(bool)), this, SLOT(senddata()));connect(tcpsocket, SIGNAL(readyRead()), this, SLOT(recvdata()));
}Widget::~Widget()
{}

四、小项目

实现一个类似于监控的东西

就是把传输内容换成了照片

客户端:

#ifndef WIDGET_H
#define WIDGET_H#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include class Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = 0);~Widget();public slots:void startv(){readsize = true;sockv = new QTcpSocket(this);connect(sockv, SIGNAL(readyRead()), this, SLOT(recv_show()));sockv->connectToHost(QHostAddress(leip->text()), atoi(leport->text().toStdString().c_str()));btstart->setText("STOP");leip->setDisabled(true);leport->setDisabled(true);disconnect(btstart, SIGNAL(clicked()), this, SLOT(startv()));connect(btstart, SIGNAL(clicked()), this, SLOT(stop()));}void stop(){sockv->close();sockv->deleteLater();disconnect(btstart, SIGNAL(clicked()), this, SLOT(stop()));connect(btstart, SIGNAL(clicked()), this, SLOT(startv()));leip->setDisabled(false);leport->setDisabled(false);btstart->setText("START");}void recv_show(){if(readsize){ //接收图片大小char buf[10] = {0};sockv->read(buf, 10);picsize = atoi(buf); //转成整形大小值//       qDebug()<bytesAvailable() < picsize) //等待图片内容接收完整return;char buf[640*480*3];sockv->read(buf, picsize);QPixmap pix;pix.loadFromData((uchar*)buf, picsize, "jpeg");lbvideo->setPixmap(pix);//切换照片readsize = true;}}private:QLabel *lbvideo, *lbip, *lbport;QLineEdit *leip, *leport;QPushButton *btstart;QTcpSocket *sockv;bool readsize;int picsize;};#endif // WIDGET_H
#include "widget.h"
#include 
#include Widget::Widget(QWidget *parent): QWidget(parent)
{lbvideo = new QLabel;lbvideo->setFixedSize(640,480);lbvideo->setScaledContents(true);lbip = new QLabel("IP");lbport = new QLabel("PORT");leip = new QLineEdit("192.168.3.27");leport = new QLineEdit("8888");btstart = new QPushButton("START");QHBoxLayout *hbox = new QHBoxLayout;hbox->addWidget(lbip);hbox->addWidget(leip);hbox->addWidget(lbport);hbox->addWidget(leport);hbox->addWidget(btstart);QVBoxLayout *vbox = new QVBoxLayout;vbox->addLayout(hbox);vbox->addWidget(lbvideo);setLayout(vbox);connect(btstart, SIGNAL(clicked()), this, SLOT(startv()));
}Widget::~Widget()
{}

服务器:

#ifndef WIDGET_H
#define WIDGET_H#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include class Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = 0);~Widget();
public slots:void show_pic(int i, QImage img){QPixmap pix(1920, 1080);
#if 1pix.fill(Qt::red);pix = pix.fromImage(img);lb_pic->setPixmap(pix);
#elselb_pic->setPixmap(QPixmap::fromImage(img));#endif
//        qDebug()<isWritable()){
//            qDebug()<<"sending "<write(buf, 10);//发大小(大小值先转换成字符串装在固定的10个字节的buff中发送)//          qDebug()<<"size ok";
#if 0QByteArray data = tem.readAll();           
#elseQByteArray data(tem.buffer());
#endifclient->write(data);//发图片内容//          qDebug()<<"finish";tem.close();}}void accept_client(){if(NULL != client){client->close();client->deleteLater();}client = myserver->nextPendingConnection();connect(client, SIGNAL(disconnected()), this, SLOT(client_close()));}void client_close(){client->close();client->deleteLater();client = NULL;}
protected:virtual voidtimerEvent(QTimerEvent *event){imageCapture->capture();
//        qDebug()<<"tttt";}private:QCamera *camera;QCameraViewfinder *viewfinder;QCameraImageCapture *imageCapture;QLabel *lb_pic;QTcpServer *myserver;QTcpSocket *client;
};#endif // WIDGET_H
#include "widget.h"
#include 
#include Widget::Widget(QWidget *parent): QWidget(parent)
{camera = new QCamera("/dev/video0"); //"/dev/video0" 摄像头设备文件,视情况而定viewfinder = new QCameraViewfinder(this);viewfinder->setFixedSize(640,480);viewfinder->show();lb_pic = new QLabel(this);myserver = new QTcpServer(this);client = NULL;camera->setViewfinder(viewfinder);QHBoxLayout *hbox = new QHBoxLayout;hbox->addWidget(viewfinder);hbox->addWidget(lb_pic);this->setLayout(hbox);imageCapture = new QCameraImageCapture(camera);camera->setCaptureMode(QCamera::CaptureStillImage);connect(imageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(show_pic(int,QImage)));connect(myserver, SIGNAL(newConnection()), this, SLOT(accept_client()));this->startTimer(3);myserver->listen(QHostAddress::AnyIPv4, 8888);camera->start();
}Widget::~Widget()
{}

---------------------------------------------------------------------------------------------------------------------------------

发文不通过只能写点”废话“了。学了一个星期的QT感觉其实不难,就是把一些封装好的类组合起来形成一些图形化界面。感觉还是挺好用,起码和C有相通性,唯一的难点应该在C++的语法上。所以会C++的同学应该更加的得心应手。挺好玩的,等学完驱动试试拿QT开发两个项目练练手。比如电视剧里男主给女主写的那个小猪闹钟,非常可爱以前不知道怎么下手做,学完QT我好像知道应该怎么写了。然后我还想做一个类似于QQ微信这种的聊天工具,可惜还不知道怎么用私网和私网通信。难道和女神之间搞点浪漫的东西还要租两台云服务器嘛,那也太扫兴了。现在这ip都是192.168开头的不能直接通信。听朋友说java有个内网透传技术是干这个的。不知道用C怎么实现。不过服务器我虽然买不起但是我打算自己买点件搭建一个服务器。应该会很有意思。

---------------------------------------------------------------------------------------------------------------------------------

相关内容

热门资讯

安卓子系统windows11,... 你知道吗?最近科技圈可是炸开了锅,因为安卓子系统在Windows 11上的兼容性成了大家热议的话题。...
电脑里怎么下载安卓系统,电脑端... 你有没有想过,你的电脑里也能装上安卓系统呢?没错,就是那个让你手机不离手的安卓!今天,就让我来带你一...
索尼相机魔改安卓系统,魔改系统... 你知道吗?最近在摄影圈里掀起了一股热潮,那就是索尼相机魔改安卓系统。这可不是一般的改装,而是让这些专...
安卓系统哪家的最流畅,安卓系统... 你有没有想过,为什么你的手机有时候像蜗牛一样慢吞吞的,而别人的手机却能像风一样快?这背后,其实就是安...
安卓最新系统4.42,深度解析... 你有没有发现,你的安卓手机最近是不是有点儿不一样了?没错,就是那个一直在默默更新的安卓最新系统4.4...
android和安卓什么系统最... 你有没有想过,你的安卓手机到底是用的是什么系统呢?是不是有时候觉得手机卡顿,运行缓慢,其实跟这个系统...
平板装安卓xp系统好,探索复古... 你有没有想过,把安卓系统装到平板上,再配上XP系统,这会是怎样一番景象呢?想象一边享受着安卓的便捷,...
投影仪装安卓系统,开启智能投影... 你有没有想过,家里的老式投影仪也能焕发第二春呢?没错,就是那个曾经陪你熬夜看电影的“老伙计”,现在它...
安卓系统无线车载carplay... 你有没有想过,开车的时候也能享受到苹果设备的便利呢?没错,就是那个让你在日常生活中离不开的iOS系统...
谷歌安卓8系统包,系统包解析与... 你有没有发现,手机更新换代的速度简直就像坐上了火箭呢?这不,最近谷歌又发布了安卓8系统包,听说这个新...
微软平板下软件安卓系统,开启全... 你有没有想过,在微软平板上也能畅享安卓系统的乐趣呢?没错,这就是今天我要跟你分享的神奇故事。想象你手...
coloros是基于安卓系统吗... 你有没有想过,手机里的那个色彩斑斓的界面,背后其实有着一个有趣的故事呢?没错,我要说的就是Color...
安卓神盾系统应用市场,一站式智... 你有没有发现,手机里的安卓神盾系统应用市场最近可是火得一塌糊涂啊!这不,我就来给你好好扒一扒,看看这...
黑莓平板安卓系统升级,解锁无限... 亲爱的读者们,你是否还记得那个曾经风靡一时的黑莓手机?那个标志性的全键盘,那个独特的黑莓体验,如今它...
安卓文件系统采用华为,探索高效... 你知道吗?最近安卓系统在文件管理上可是有了大动作呢!华为这个科技巨头,竟然悄悄地给安卓文件系统来了个...
深度系统能用安卓app,探索智... 你知道吗?现在科技的发展真是让人惊叹不已!今天,我要给你揭秘一个超级酷炫的话题——深度系统能用安卓a...
安卓系统的分区类型,深度解析存... 你有没有发现,你的安卓手机里藏着不少秘密?没错,就是那些神秘的分区类型。今天,就让我带你一探究竟,揭...
安卓系统铠无法兑换,揭秘无法兑... 最近是不是有很多小伙伴在玩安卓系统的游戏,突然发现了一个让人头疼的问题——铠无法兑换!别急,今天就来...
汽车安卓系统崩溃怎么刷,一键刷... 亲爱的车主朋友们,你是否曾遇到过汽车安卓系统崩溃的尴尬时刻?手机系统崩溃还能重启,但汽车系统崩溃了,...
miui系统可以刷安卓p系统吗... 亲爱的手机控们,你是否对MIUI系统情有独钟,同时又对安卓P系统的新鲜功能垂涎欲滴?今天,就让我带你...