初学者记录学习内容,如有错误请各位前辈指点。
这次的项目实现将在上次完成“单幅图片从客户端发送到服务器”的基础上继续添加。
主要添加的功能的是
①客户端和服务器可以选择读取和保存图片的文件,而不是存入到内存中。
②发送接收不同格式的图片。
③服务器读取文件中所有的图片,显示到界面上,并且可以切换图片。
服务器Server
服务器端的界面依旧是那样的简洁
sendButton发送图片,disconnectButton断开连接,picturePathEdit得出读取图片的路径,saveButton选择路径。
直接贴代码:
filepictureserver.h
#ifndef FILEPICTURESERVER_H
#define FILEPICTURESERVER_H
#include <QDialog>
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QStringList>
#include <vector>
#include <QByteArray>
#include <QDataStream>
#include <QBuffer>
#include <QString>
using namespace std;//std::vector
namespace Ui {
class filePictureServer;
}
class filePictureServer : public QDialog
{
Q_OBJECT
public:
explicit filePictureServer(QWidget *parent = 0);
~filePictureServer();
private slots:
void sendPictures();
void showDirectory();
void disconnectSocket();
void acceptConnection();
void displayError(QAbstractSocket::SocketError);
private:
Ui::filePictureServer *ui;
QTcpServer *tcpServer;
QTcpSocket *tcpSocket;
QFileDialog *fileDialog;
QStringList pictureString_list;
vector<QPixmap> picturelist;
int picIndex;
};
#endif // FILEPICTURESERVER_H
filepictureserver.cpp
#include "filepictureserver.h"
#include "ui_filepictureserver.h"
#include <windows.h>
#include "utility.h"
filePictureServer::filePictureServer(QWidget *parent) :
QDialog(parent),
ui(new Ui::filePictureServer)
{
ui->setupUi(this);
tcpServer = new QTcpServer(this);
if(!tcpServer->listen(QHostAddress::Any,7777))
{
qDebug()<<tcpServer->errorString();
close();
}
tcpSocket = NULL;
connect(ui->sendButton,SIGNAL(clicked(bool)),this,SLOT(sendPictures()));
connect(ui->saveButton,SIGNAL(clicked(bool)),this,SLOT(showDirectory()));
connect(ui->disconnectButton,SIGNAL(clicked(bool)),this,SLOT(disconnectSocket()));
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(acceptConnection()));
picIndex = 0;
}
filePictureServer::~filePictureServer()
{
delete ui;
}
void filePictureServer::sendPictures()
{
if(tcpSocket==NULL)
return;
QByteArray block;
QBuffer buffer;
QString style;
QDataStream out(&block,QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_8);
style = pictureString_list[picIndex].right(3);
picturelist[picIndex].save(&buffer,style.toStdString().c_str());
picIndex++;
out<<(quint32)buffer.data().size();
out<<style;
block.append(buffer.data());
tcpSocket->write(block);
if(picIndex>=picturelist.size())
picIndex = 0;
}
void filePictureServer::showDirectory()
{
fileDialog=ne