无法在客户端发送的服务器中接收文件名

时间:2015-11-23 04:24:28

标签: sockets

我正在尝试编写一个简单的套接字程序,它在客户端读取文件名并将其发送到服务器。如果存在,文件的内容将被发送回客户端。客户端和服务器能够成功连接,但是当我读取文件名时,我没有得到任何输出(程序没有终止)。请告诉我出了什么问题。

server.c

int main()
{
int create_socket,new_socket,fd,addlen,n;
int bufsize=1024;
char *buffer=malloc(bufsize);
char fname[255];
struct sockaddr_in address;

//printf("program");    
if((create_socket=socket(AF_INET,SOCK_STREAM,0))>0)
printf("socket created");

address.sin_family=AF_INET;
address.sin_port=htons(15000);
address.sin_addr.s_addr=INADDR_ANY;

if(bind(create_socket,(struct sockaddr*)&address,sizeof(address))==0)
printf("socket binded");
    while(1)

{
    printf("Inside while loop");
    listen(create_socket,3);
    addlen=sizeof(struct sockaddr_in);
    if(new_socket=accept(create_socket,(struct sockaddr*)&address,&addlen)>0)
    printf("%d connected",inet_ntoa(address.sin_addr));
    else
    printf("not connected");

    recv(new_socket,fname,255,0);
    printf("file name is %s",fname);
    if(fd=open(fname,O_RDONLY)<0)
    {
        strcpy(buffer,"Not such file found");
        send(new_socket,buffer,sizeof(buffer),0);
    }
    else
    {
        while(n=read(fd,buffer,bufsize)>0)
        send(new_socket,buffer,n,0);
    }
    close(new_socket);
}
close(create_socket);

}

client.c

int main(int argc,char *argv[])
{
int create_socket,n;
int bufsize=1024;
char *buffer=malloc(bufsize);
char fname[255];
struct sockaddr_in address;

if((create_socket=socket(AF_INET,SOCK_STREAM,0))>0)
printf("socket created\n");

address.sin_family=AF_INET;
address.sin_port=htons(15000);
inet_pton(AF_INET,argv[1],&address.sin_addr);



    if(connect(create_socket,(struct sockaddr*)&address,sizeof(address))==0)
    printf("%s connected\n",argv[1]);
    else
    printf("not connected\n");

    printf("Enter the filename\n");
    scanf("%s",fname);
    send(create_socket,fname,strlen(fname),0);

    printf("get the values");

        while(n=recv(create_socket,buffer,bufsize,0)>0)
        write(1,buffer,n);



return close(create_socket);

}

0 个答案:

没有答案