QT TCP文件上传服务器

时间:2022-01-23 08:28:46
利用QT做为client端,纯C语言做为server端,利用tcp协议,实现client端向server端传递文件
Linux服务器端
//头文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h> #define MAX_SOCKET 100 #ifdef __cplusplus
extern "C"
{
#endif //create socket
int create_socket(int port); //accept client
int accept_client(int st); //recv message
int recv_msg(int st); #ifdef __cplusplus
}
#endif
//辅助方法
#include "pub.h" //create socket
int create_socket(int port)
{
if (port < )
{
printf("create_socket() param not correct!\n");
return -;
}
int st = socket(AF_INET, SOCK_STREAM, );
if (st < )
{
printf("socket() failed ! error message:%s\n", strerror(errno));
return -;
}
int on = ;
if (setsockopt(st, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < )
{
printf("setsockopt() failed ! error message:%s\n", strerror(errno));
close(st);
return -;
}
struct sockaddr_in addr;
memset(&addr, , sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(st, (struct sockaddr *) &addr, sizeof(addr)) < )
{
printf("bind() failed ! error message:%s\n", strerror(errno));
close(st);
return -;
}
if (listen(st, MAX_SOCKET) < )
{
printf("listen() failed ! error message:%s\n", strerror(errno));
close(st);
return -;
}
return st;
} //网络地址转化字符串
void sockaddr_toa(const struct sockaddr_in *addr, char *ipaddr)
{
if (addr == NULL || ipaddr == NULL)
{
printf("sockaddr_toa() param nor correct!\n");
return;
}
unsigned char *p = (unsigned char *) &(addr->sin_addr.s_addr);
sprintf(ipaddr, "%u:%u:%u:%u", p[], p[], p[], p[]);
} //accept client
int accept_client(int st)
{
if (st < )
{
printf("accept_client() param not correct!\n");
return -;
}
struct sockaddr_in addr;
memset(&addr, , sizeof(addr));
socklen_t len = sizeof(addr);
int client_st = accept(st, (struct sockaddr *) &addr, &len);
if (client_st < )
{
printf("accept() failed ! error message :%s\n", strerror(errno));
return -;
}
char buf[] = { };
sockaddr_toa(&addr, buf);
printf("accept by %s\n", buf);
return client_st;
} //recv message
int recv_msg(int st)
{
if (st < )
{
printf("recv_msg() param not correct!\n");
return -;
}
//
char buf[] = { };
int rc = recv(st, buf, sizeof(buf), );
if (rc < )
{
printf("recv() failed ! error message:%s\n",strerror(errno));
return -;
} else if (rc == )
{
printf("client is closed!\n");
return -;
}
//open the file
FILE * pfw = NULL;
pfw = fopen(buf, "w");
if (pfw == NULL)
{
printf("fopen() failed! error message:%s\n", strerror(errno));
return -;
}
memset(buf, , sizeof(buf));
strcpy(buf, "OK");
//给客户端发送"OK"
if (send(st, buf, strlen(buf), ) <= )
{
printf("send() failed! error message:%s\n", strerror(errno));
return -;
}
while ()
{
memset(buf, , sizeof(buf));
rc = recv(st, buf, sizeof(buf), );
if (rc < )
{
printf("recv() failed ! error message:%s\n",strerror(errno));
return -;
} else if (rc == )
{
printf("client is closed!\n");
break;
}
fwrite(buf, sizeof(char), rc, pfw);
}
//关闭客户端
close(st);
printf("文件接收完毕!\n");
return ;
}
//服务器端
#include "pub.h" int main(int arg,char *args[])
{
if(arg<)
{
printf("please print one param ! \n");
return -;
}
int port=atoi(args[]);
int listen_st=create_socket(port);
if(listen_st<) return -;
int client_st=accept_client(listen_st);
if(client_st<) return -;
recv_msg(client_st);
close(listen_st);
return ;
}
.SUFFIXES:.c .o
CC=gcc
SRCS=mserver.c\
pub.c
OBJS=$(SRCS:.c=.o)
EXEC=mser start:$(OBJS)
$(CC) -o $(EXEC) $(OBJS)
@echo "--------OK--------"
.c.o:
$(CC) -Wall -g -o $@ -c $<
clean:
rm -f $(OBJS)
rm -f $(EXEC)
QT客户端
#ifndef WIDGET_H
#define WIDGET_H #include <QWidget>
#include <QTcpSocket>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QTextBrowser> class Widget : public QWidget
{
Q_OBJECT public:
Widget(QWidget *parent = );
~Widget();
private:
QTcpSocket *tcpsock;
QLabel *label1,*label2,*label3;
QLineEdit *edit1,*edit2;
QPushButton *btn1;
QTextBrowser *text1;
QString filename;
void mygetfilename(const char *src,int len,char *dest);
private slots:
void btn1_click();
void myrecvdata();
}; #endif // WIDGET_H
#include "widget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFileDialog>
#include <QMessageBox>
#include <QHostAddress> Widget::Widget(QWidget *parent)
: QWidget(parent)
{
tcpsock=new QTcpSocket(this);
connect(tcpsock,SIGNAL(readyRead()),this,SLOT(myrecvdata()));
label1=new QLabel(tr("IP地址:"));
label2=new QLabel(tr("端口号:"));
label3=new QLabel(tr("上传信息"));
edit1=new QLineEdit(); edit2=new QLineEdit();
btn1=new QPushButton(tr("文件上传"));
text1=new QTextBrowser();
connect(btn1,SIGNAL(clicked()),this,SLOT(btn1_click()));
QHBoxLayout *lay1=new QHBoxLayout();
lay1->addWidget(label1);
lay1->addWidget(edit1); QHBoxLayout *lay2=new QHBoxLayout();
lay2->addWidget(label2);
lay2->addWidget(edit2); QHBoxLayout *lay4=new QHBoxLayout();
lay4->addWidget(btn1);
lay4->addStretch(); QVBoxLayout *lay3=new QVBoxLayout(this);
lay3->addLayout(lay1);
lay3->addLayout(lay2);
lay3->addLayout(lay4);
lay3->addWidget(label3);
lay3->addWidget(text1);
} //接收信息
void Widget::myrecvdata()
{
//接收消息
char buf[]={};
if(tcpsock->bytesAvailable()>)
{
tcpsock->read(buf,sizeof(buf));
if(strncmp(buf,"OK",)==)
{
text1->append("服务器返回OK!");
//发送文件
FILE *pfr=NULL;
pfr=fopen(filename.toStdString().data(),"rb");
if(pfr==NULL)
{
QMessageBox::critical(this,tr("错误信息"),"打开文件失败!");
return;
}
int rc=;
while(!feof(pfr))
{
//
memset(buf,,sizeof(buf));
rc=fread(buf,,sizeof(buf),pfr);
//发送数据
tcpsock->write(buf,rc);
}
fclose(pfr);
pfr=NULL;
text1->append("文件发送成功!");
}
} } //获取文件名
void Widget::mygetfilename(const char *src,int len,char *dest)
{
if(src==NULL||len==||dest==NULL)
{
QMessageBox::critical(this,tr("错误信息"),"mygetfilename()参数不可以为空!");
return;
}
int i=;
for(i=len-;i>=;i--)
{
if(src[i]=='/'||src[i]=='\\')
{
strcpy(dest,src+i+);
break;
}
}
} //点击文件上传
void Widget::btn1_click()
{
//获取IP地址
QString ipaddr=edit1->text();
if(ipaddr.isEmpty())
{
QMessageBox::critical(this,tr("错误信息"),"请填写IP地址!");
return;
}
//获取端口号
QString port=edit2->text();
if(port.isEmpty())
{
QMessageBox::critical(this,tr("错误信息"),"请填写端口号!");
return;
}
filename=QFileDialog::getOpenFileName();
if(filename.isEmpty()) return;
char buf[]={};
//获取文件名
mygetfilename(filename.toStdString().data(),filename.toStdString().length(),buf);
if(strlen(buf)==)
{
QMessageBox::critical(this,tr("错误信息"),"文件格式不正确!");
return;
}
tcpsock->close();
//绑定端口号
QHostAddress *serip=new QHostAddress();
serip->setAddress(ipaddr);
tcpsock->connectToHost(ipaddr,port.toInt());
delete serip;
//发送数据
tcpsock->write(buf,strlen(buf));
text1->append("开始发送数据!");
} Widget::~Widget()
{ }