当前位置: 动力学知识库 > 问答 > 编程问答 >

Cpp socket program waits indefinitely on send() and recv() function

问题描述:

I was implementing a cpp socket file transfer program.The server will send the list of files available and the client will reply with the name of file.Sending of the list is successful but while receving the program waits indefinitely.Please help !!.

#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);

}

Client Side Code :

#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);

}

分享给朋友:
您可能感兴趣的文章:
随机阅读: