Cpp套接字程序无限期地等待send()和recv()函数

时间:2015-03-11 15:28:32

标签: sockets wait file-transfer

我正在实现一个cpp套接字文件传输程序。服务器将发送可用文件列表,客户端将回复文件名。列表发送成功,但接收程序无限期等待。请帮忙! !

#include <unistd.h>

#include <string>
#include <stdio.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <fstream>
#include <iostream>
#define LIMIT 250
#define PORT 3490

using namespace std;
int main()
{
    int sockfd,clisockfd,portno;
    char buffer[LIMIT]={0};
    char buff;
    struct addrinfo serv,*res,cli;
    memset(&serv,0,sizeof (serv));
    serv.ai_family=AF_UNSPEC;
    serv.ai_socktype=SOCK_STREAM;
    serv.ai_flags=AI_PASSIVE;

    getaddrinfo(NULL,"5000",&serv,&res);
    sockfd=socket(res->ai_family,res->ai_socktype,res->ai_protocol);
    bind(sockfd,res->ai_addr,res->ai_addrlen);
    listen(sockfd,1);
    int cli_len=sizeof(cli);
    clisockfd=accept(sockfd,(struct sockaddr *)&cli,(socklen_t *)&cli_len);

    ifstream ls("list.txt");
    int i=0;

    while(ls.getline(buffer,LIMIT))
    {
        send(clisockfd,buffer,strlen(buffer),0);
        send(clisockfd,"\n",1,0);
        cout<<buffer<<endl;
    }
    while(recv(clisockfd,&s,1,0))
    cout<<s;
    close(clisockfd);
   }

客户端代码:

#include <unistd.h>
#include <string>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <iostream>
#define LIMIT 250
using namespace std;

int main()
{

    int sockfd;
    char buffer;
    struct addrinfo cli,*res;
    memset(&cli,0,sizeof(cli));
    cli.ai_family=AF_UNSPEC;
    cli.ai_socktype=SOCK_STREAM;

    getaddrinfo("127.0.0.1","5000",&cli,&res);
    sockfd=socket(res->ai_family,res->ai_socktype,res->ai_protocol);

    if(connect(sockfd,res->ai_addr,res->ai_addrlen)==-1)
    {
      perror("error connecting");
    }

    cout<<"The Files Present on the server are:\n";
    while(recv(sockfd,&buffer,1,0))
    {
     cout<<buffer;
     }     
     char req[20];
     cout<<"Enter the file to Download\n";
     cin>>req;

     send(sockfd,req,sizeof(req),0);

     close(sockfd);
     }

0 个答案:

没有答案