1.server.h
#ifndef SERVER_H
#define SERVER_H
#include <QMainWindow>
#include<QLabel>
#include<QtNetwork/QHostInfo>
#include<QtNetwork/QTcpServer>
#include<QtNetwork/QTcpSocket>
#include<QFile>
namespace Ui {
class Server;
}
class Server : public QMainWindow
{
Q_OBJECT
private:
QLabel *LabListen;
QLabel *LabSocketState;
QTcpServer *tcpServer;
QTcpSocket *tcpSocket;
QString getlocalIP();
private:
QTcpServer *fileServer;
QTcpSocket *fileSocket;
qint64 totalBytes;
qint64 bytesReceived;
qint64 bytestoWrite;
qint64 bytesWritten;
qint64 filenameSize;
QString filename;
QString m_imgDirPath;
qint64 perDataSize;
QFile *localFile;
QByteArray inBlock;
QByteArray outBlock;
void initSocket();
void initFileSocket();
private slots:
void onNewConnection();
void onSocketStateChange(QAbstractSocket::SocketState socketState);
void onClientConnected();
void onClientDisconnected();
void onSocketReadyRead();
void acceptFileConnection();
void updateFileProgress();
void displayError(QAbstractSocket::SocketError socketError);
void updateFileProgress(qint64);
void on_imgListWidget_clicked(const QModelIndex &index);
protected:
void closeEvent(QCloseEvent *event);
private slots:
void on_acHostInfo_triggered();
void on_actStart_triggered();
void on_actStop_triggered();
void on_btnSendMsg_clicked();
void on_btnSaveDir_clicked();
void on_btnSelectFile_clicked();
void on_btnSendFile_clicked();
void Auto_get_mac_IP();
void on_choose_image_pushButton_clicked();
void on_closeimage_pushButton_clicked();
void on_actClear_triggered();
public:
explicit Server(QWidget *parent = 0);
~Server();
private:
Ui::Server *ui;
};
#endif
2、main.c
#include "server.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Server w;
w.show();
return a.exec();
}
3、server.cpp
#include "server.h"
#include "ui_server.h"
#include<QFileDialog>
#include <QMessageBox>
#include <QMainWindow>
#include <QMovie>
#include <QDebug>
#include <QDateTime>
#include <QSettings>
#include <qnetworkinterface.h>
QString Server::getlocalIP()
{
QString hostName=QHostInfo::localHostName();
QHostInfo hostInfo=QHostInfo::fromName(hostName);
QList<QHostAddress> addList=hostInfo.addresses();
if(!addList.isEmpty())
for(int i=0;i<addList.count();i++)
{
QHostAddress localIP =addList.at(i);
if(localIP.protocol()==QAbstractSocket::IPv4Protocol)
return localIP.toString();
}
return "";
}
Server::Server(QWidget *parent) :QMainWindow(parent), ui(new Ui::Server)
{
ui->setupUi(this);
this->setWindowTitle("Tcp Server");
initSocket();
initFileSocket();
Auto_get_mac_IP();
ui->image_label->setStyleSheet("background-color:rgb(222, 222, 222);");
ui->imgListWidget->setStyleSheet("background-color:rgb(222, 222, 222);");
ui->plainTextEdit->setStyleSheet("background-color:rgb(222, 222, 222);");
ui->fg_label->setStyleSheet("QLabel{background-color:rgb(143, 0, 0);}");
ui->fg_label->setStyleSheet("background-color:rgb(143, 0, 0);font-size:18px;color:white");
ui->img_label->setStyleSheet("QLabel{background-color:rgb(143, 0, 0);}");
ui->img_label->setStyleSheet("background-color:rgb(143, 0, 0);font-size:18px;color:white");
ui->information_prompt_area_laber->setStyleSheet("background-color:rgb(143, 0, 0);font-size:18px;color:white");
ui->Picture_display_area_label->setStyleSheet("background-color:rgb(143, 0, 0);font-size:18px;color:white");
}
void Server::Auto_get_mac_IP()
{
QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();
foreach(QNetworkInterface interface,list)
{
qDebug() << "Device: "<<interface.name();
qDebug() << "HardwareAddress: "<<interface.hardwareAddress();
if(interface.name()=="enp2s0"|interface.name()=="ethernet_32774")
{
QList<QNetworkAddressEntry> entryList = interface.addressEntries();
foreach(QNetworkAddressEntry entry,entryList)
{
if( entry.ip().toString().size() < 16)
{
qDebug()<<"IP Address: "<<entry.ip().toString();
qDebug()<<"Netmask: " <<entry.netmask().toString();
qDebug()<<"Broadcast: "<<entry.broadcast().toString();
ui->editIP->clear();
ui->editIP->setText(QString (entry.ip().toString()));
}
}
}
}
}
void Server::on_acHostInfo_triggered()
{
Auto_get_mac_IP();
}
void Server::initSocket()
{
LabListen=new QLabel("监听状态:");
LabListen->setMinimumWidth(150);
ui->statusBar->addWidget(LabListen);
LabSocketState=new QLabel("Socket状态:");
LabSocketState->setMinimumWidth(200);
ui->statusBar->addWidget(LabSocketState);
tcpServer=new QTcpServer(this);
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));
}
void Server::initFileSocket()
{
perDataSize = 64*1024;
totalBytes = 0;
bytestoWrite = 0;
bytesWritten = 0;
bytesReceived = 0;
filenameSize = 0;
fileSocket = new QTcpSocket(this);
fileServer = new QTcpServer(this);
quint16 port=ui->spinPort->value()+1;
qDebug()<<"initFileSocket"<<port;
fileServer->listen(QHostAddress::Any,ui->spinPort->value()+1);
connect(fileServer,SIGNAL(newConnection()),this,SLOT(acceptFileConnection()));
}
Server::~Server()
{
delete ui;
delete tcpServer;
delete fileServer;
}
void Server::on_actStart_triggered()
{
const QString address_IP=ui->editIP->text();
quint16 port=ui->spinPort->value();
const QHostAddress address=(address_IP=="Any")?QHostAddress::Any:QHostAddress(address_IP);
tcpServer->listen(address,port);
tcpServer->listen(QHostAddress::LocalHost,port);
ui->plainTextEdit->appendPlainText("**开始监听...");
ui->plainTextEdit->appendPlainText("**服务器地址:"+tcpServer->serverAddress().toString());
ui->plainTextEdit->appendPlainText("**服务器端口:"+QString::number(tcpServer->serverPort()));
ui->actStart->setEnabled(false);
ui->actStop->setEnabled(true);
LabListen->setText("监听状态:正在监听");
}
void Server::on_actStop_triggered()
{
if (tcpServer->isListening())
{
tcpServer->close();
ui->actStart->setEnabled(true);
ui->actStop->setEnabled(false);
LabListen->setText("监听状态:已停止监听");
}
}
void Server::onNewConnection()
{
ui->plainTextEdit->appendPlainText("有新连接");
tcpSocket = tcpServer->nextPendingConnection();
connect(tcpSocket, SIGNAL(connected()),this, SLOT(onClientConnected()));
connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(onClientDisconnected()));
connect(tcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this,SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
onSocketStateChange(tcpSocket->state());
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(onSocketReadyRead()));
qDebug()<<"Client connected success.";
}
void Server::onSocketStateChange(QAbstractSocket::SocketState socketState)
{
switch(socketState)
{
case QAbstractSocket::UnconnectedState:
LabSocketState->setText("scoket状态:UnconnectedState");
break;
case QAbstractSocket::HostLookupState:
LabSocketState->setText("scoket状态:HostLookupState");
break;
case QAbstractSocket::ConnectingState:
LabSocketState->setText("scoket状态:ConnectingState");
break;
case QAbstractSocket::ConnectedState:
LabSocketState->setText("scoket状态:ConnectedState");
break;
case QAbstractSocket::BoundState:
LabSocketState->setText("scoket状态:BoundState");
break;
case QAbstractSocket::ClosingState:
LabSocketState->setText("scoket状态:ClosingState");
break;
case QAbstractSocket::ListeningState:
LabSocketState->setText("scoket状态:ListeningState");
}
}
void Server::onClientConnected()
{
ui->plainTextEdit->appendPlainText("**client socket connected");
ui->plainTextEdit->appendPlainText("**peer address:"+tcpSocket->peerAddress().toString());
ui->plainTextEdit->appendPlainText("**peer port:"+QString::number(tcpSocket->peerPort()));
}
void Server::onClientDisconnected()
{
ui->plainTextEdit->appendPlainText("**client socket disconnected");
tcpSocket->deleteLater();
}
void Server::onSocketReadyRead()
{
ui->plainTextEdit->appendPlainText("[in] "+tcpSocket->readAll());
}
void Server::on_btnSendMsg_clicked()
{
QString msg=ui->editMsg->text();
ui->plainTextEdit->appendPlainText("[out] "+msg);
ui->editMsg->clear();
ui->editMsg->setFocus();
QByteArray str=msg.toUtf8();
tcpSocket->write(str);
}
void Server::closeEvent(QCloseEvent *event)
{
if (tcpServer->isListening())
tcpServer->close();
if (fileServer->isListening())
fileServer->close();
event->accept();
}
void Server::acceptFileConnection()
{
bytesWritten = 0;
perDataSize = 64*1024;
fileSocket =fileServer->nextPendingConnection();
connect(fileSocket,SIGNAL(readyRead()),this,SLOT(updateFileProgress()));
connect(fileSocket,SIGNAL(bytesWritten(qint64)),this,SLOT(updateFileProgress(qint64)));
connect(fileSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));
}
void Server::updateFileProgress()
{
QDataStream inFile(fileSocket);
inFile.setVersion(QDataStream::Qt_5_6);
ui->plainTextEdit->appendPlainText("updateFileProgress");
if(bytesReceived <= sizeof(qint64)*2)
{
QByteArray bytes = NULL;
while(this->fileSocket->waitForReadyRead(100))
{
qDebug()<<"Data receiving...";
bytes.append(this->fileSocket->readAll());
}
if(this->fileSocket->isWritable())
{
}
else
{
qDebug()<<"Cannot send back data to Client.";
}
QPixmap pixmap;
pixmap.loadFromData(bytes);
int with = ui->image_label->width();
int height = ui->image_label->height();
QPixmap fitpixmap = pixmap.scaled(with, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);
ui->image_label->setPixmap(fitpixmap);
QDateTime datetime;
QString timestr = datetime.currentDateTime().toString("yyyyMMddHHmmss");
filename = ui->editSaveDir->text()+"/"+timestr+".png";
qDebug()<<"filename"<<filename;
localFile = new QFile(filename);
if(!localFile->open(QFile::WriteOnly))
{
ui->plainTextEdit->appendPlainText("Server::open file error!");
return;
}
localFile->write(bytes);
bytes.resize(0);
}
if(bytesReceived <= sizeof(qint64)*2)
{
if((fileSocket->bytesAvailable()>=(sizeof(qint64))*2) && (filenameSize==0))
{
inFile>>totalBytes>>filenameSize;
bytesReceived += sizeof(qint64)*2;
qDebug()<<"filenameSize success."<< filenameSize;
}
if((fileSocket->bytesAvailable()>=filenameSize) && (filenameSize != 0))
{
inFile>>filename;
bytesReceived += filenameSize;
filename = ui->editSaveDir->text()+"/"+filename;
localFile = new QFile(filename);
if(!localFile->open(QFile::WriteOnly))
{
ui->plainTextEdit->appendPlainText("Server::open file error!");
return;
}
}
else
return;
}
if(bytesReceived < totalBytes)
{
bytesReceived += fileSocket->bytesAvailable();
inBlock = fileSocket->readAll();
localFile->write(inBlock);
inBlock.resize(0);
}
this->ui->progressBarRec->setMaximum(totalBytes);
this->ui->progressBarRec->setValue(bytesReceived);
if(bytesReceived == totalBytes)
{
this->ui->plainTextEdit->appendPlainText("Receive file successfully!");
bytesReceived = 0;
totalBytes = 0;
filenameSize = 0;
localFile->close();
}
}
void Server::updateFileProgress(qint64 numBytes)
{
bytesWritten += (int)numBytes;
if(bytestoWrite > 0)
{
outBlock = localFile->read(qMin(bytestoWrite,perDataSize));
bytestoWrite -= ((int)fileSocket->write(outBlock));
outBlock.resize(0);
}
else
localFile->close();
this->ui->progressBarSend->setMaximum(totalBytes);
this->ui->progressBarSend->setValue(bytesWritten);
qDebug()<<"bytesWritten"<<bytesWritten<<"--"<<"totalBytes"<<totalBytes;
if(bytesWritten == totalBytes)
{
bytesWritten=0;totalBytes=0;
localFile->close();
qDebug()<<ui->progressBarRec->value()<<"value";
qDebug()<<ui->progressBarRec->maximum()<<"maximum";
}
}
void Server::displayError(QAbstractSocket::SocketError socketError)
{
ui->plainTextEdit->appendPlainText(fileSocket->errorString());
}
void Server::on_btnSaveDir_clicked()
{
ui->editSaveDir->setText(QFileDialog::getExistingDirectory(this,"请选择保存路径"));
}
void Server::on_btnSelectFile_clicked()
{
filename = QFileDialog::getOpenFileName(this,"Open a file");
ui->editFile->setText(filename);
}
void Server::on_btnSendFile_clicked()
{
localFile = new QFile(filename);
if(!localFile->open(QFile::ReadOnly))
{
ui->plainTextEdit->appendPlainText("Client:open file error!");
return;
}
this->totalBytes = localFile->size();
QDataStream sendout(&outBlock,QIODevice::WriteOnly);
sendout.setVersion(QDataStream::Qt_4_8);
QString currentFileName = filename.right(filename.size()-filename.lastIndexOf('/')-1);
qDebug()<<sizeof(currentFileName);
sendout<<qint64(0)<<qint64(0)<<currentFileName;
totalBytes += outBlock.size();
sendout.device()->seek(0);
sendout<<totalBytes<<qint64((outBlock.size()-sizeof(qint64)*2));
bytestoWrite = totalBytes-fileSocket->write(outBlock);
outBlock.resize(0);
}
void Server::on_choose_image_pushButton_clicked()
{
m_imgDirPath=ui->editSaveDir->text();
QString filter;
QDir dir(m_imgDirPath);
QFileInfoList fileInfoList = dir.entryInfoList();
QString filePath;
foreach(QFileInfo fileinfo, fileInfoList )filter = fileinfo.suffix();
for(int i=0; i<fileInfoList.count(); i++)
{
filePath.clear();
filePath.append(m_imgDirPath + "/" + fileInfoList.at(i).fileName());
if(fileInfoList.at(i).fileName() == "." || fileInfoList.at(i).fileName() == "..")
{
continue;
}
QListWidgetItem *item = new QListWidgetItem(QIcon(filePath), fileInfoList.at(i).fileName());
ui->imgListWidget->addItem(item);
}
ui->img_label->setText("图片加载完成");
}
void Server::on_imgListWidget_clicked(const QModelIndex &index)
{
Q_UNUSED(index);
QString imgPath = (m_imgDirPath + "/" + ui->imgListWidget->currentItem()->text());
if(imgPath.endsWith(".gif") || imgPath.endsWith(".Gif"))
{
QMovie *movie =new QMovie(imgPath);
ui->image_label->setMovie(movie);
movie->start();
}
else
{
int with = ui->image_label->width();
int height = ui->image_label->height();
QPixmap fitpixmap = QPixmap(imgPath).scaled(with, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);
ui->image_label->setPixmap(fitpixmap);
}
}
void Server::on_closeimage_pushButton_clicked()
{
ui->image_label->clear();
ui->imgListWidget->clear();
ui->img_label->setText("请加载图片");
}
void Server::on_actClear_triggered()
{
ui->plainTextEdit->clear();
}
实际效果:
下载:https://gitee.com/pang_xi_wen/qtq.git
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)