代码实例是,客户端发送给服务端所需要的文件路径名,然后服务端将文件内容零拷贝发送给客户端,然后,客户端将内容写入到本地文件。
客户端代码:zerocopyclient.cpp
#include "network.h"
using namespace std;
int main(int argc,char *argv[])
{
sockaddr_in servaddr;
int sockfd,n;
const char * filename = "temp";
char buff[] = "/home/lbx/study/network/Makefile";
char buf[MAXLINE];
if(argc != 2)
{
cout << "argc is wrong"
<< endl;
exit(1);
}
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
sockfd = socket(AF_INET,SOCK_STREAM,0);
connect(sockfd,(SA*)&servaddr,sizeof(servaddr));
send(sockfd,buff,sizeof(buff),0);
FILE *fp = fopen(filename,"wb");
while(true)
{
if((n = recv(sockfd,buf,sizeof(buf),0)) > 0)
fwrite(buf,sizeof(char),n,fp);
else if(n == 0)
{
close(sockfd);
break;
}
else
{
cout << "recv wrong "
<< endl;
exit(1);
}
}
return 0;
}
服务端代码:zerocopyserver.cpp
#include "network.h"
using namespace std;
int main(int argc,char *argv[])
{
sockaddr_in servaddr;
int listenfd,connfd,n,fd;
struct stat filestat;
off_t offset;
char buff[MAXLINE];
servaddr.sin_port = htons(SERV_PORT);
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
listenfd = socket(AF_INET,SOCK_STREAM,0);
bind(listenfd,(SA*)&servaddr,sizeof(servaddr));
listen(listenfd,LISTENQ);
while(true)
{
connfd = accept(listenfd,NULL,NULL);
while(true)
{
n = recv(connfd,buff,sizeof(buff),0);
if(n > 0)
{
offset = 0;
stat(buff,&filestat);
fd = open(buff,O_RDONLY);
sendfile(connfd,fd,&offset,filestat.st_size);
}else if(n == 0)
{
close(connfd);
break;
}else
{
cout << "recv wrong"
<< endl;
close(connfd);
exit(1);
}
}
}
return 0;
}
零拷贝实例(zerocopy)转
最新推荐文章于 2011-06-24 02:51:00 发布