c套接字文件传输,服务器无法打开现有文件

时间:2015-09-22 19:51:09

标签: c linux sockets gcc

我正在编写简单的客户端 - 服务器程序。基本上我是关注" Linux网络编程"书。这是简单的TCP服务器

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#define SERVERPORT 8888
#define MAXBUF 1024
int main(int argc, char* argv[])
{
    int sockd;
    int counter;
    int fd;
    struct sockaddr_in fServer;
    char buf[MAXBUF];
    int status;
    if(argc<3)
    {
        printf("Incorrect data provided\n");
        exit(1);
    }
    sockd=socket(AF_INET, SOCK_STREAM,0);
    if(sockd==-1)
    {
        printf("could not create socket\n");
        exit(1);
    }
    fServer.sin_family=AF_INET;
    fServer.sin_addr.s_addr=inet_addr(argv[1]);
    fServer.sin_port=htons(SERVERPORT);
    status=connect(sockd, (struct sockaddr*)&fServer,
                sizeof(fServer));
    if(status==-1)
    {
        printf("could not connect to server\n");
        exit(1);
    }
    status=write(sockd, argv[2], strlen(argv[2]+1));
    if(status==-1)
    {
        printf("could not send file name to server\n");
        exit(1);
    }
    shutdown(sockd, SHUT_WR);

    fd=open(argv[2], O_WRONLY| O_CREAT| O_APPEND);
    if(fd==-1)
    {
        printf("could not open destination file\n");
        exit(1);
    }
    while((counter=read(sockd, buf, MAXBUF))>0)
    {
        write(fd, buf, counter);
    }
    if(counter==-1)
    {
        printf("file transfer is complete\n");
        exit(1);
    }
        printf("file transfer is complete\n");
    close(sockd);
    return 0;
}

此代码适用于客户。

socket is created
socket is waiting for connection
connection established, waiting for the file name
reading from the file
could not open the file
 error is detected: : No such file or directory
connection established, waiting for the file name
reading from the file
could not open the file
 error is detected: : No such file or directory 

我从与服务器相同的目录中传递文件名。我将filename作为agrc [2]参数传递。然而,服务器oputput是以下

        target = open(my_file, mode='wb')
        ftp.retrbinary('RETR ' + my_file, target.write)
        target.close()

我在第一次尝试时输入了文件名,然后我输入了完整路径,但仍然收到相同的消息。那么问题是什么?提前谢谢

2 个答案:

答案 0 :(得分:1)

客户端:

library(dplyr)
col1 = c(1,1,3,3,5,6,7,8,9)
col2 = c("cust1", 'cust1', 'cust3', 'cust4', 'cust5', 'cust5', 'cust5',     'cust5', 'cust6')
df1 = data.frame(col1, col2)
df1

distinct(select(df1, col1, col2))
如果你想要包含\ 0,那么

status=write(sockd, argv[2], strlen(argv[2]+1)); 应为strlen(argv[2]+1)。你也不要关闭你的fd。 strlen(argv[2])+1应为close(sockd);

服务器:
\ {1}} close(fd);如果您不确定是否收到了\ {。}。{。} 如果你发送1个字符,例如'a',我将为1,你的数组看起来像是

filename[i+1]='\0';

答案 1 :(得分:0)

与您的问题无关,但在服务器端,您应该在write()之后推进bufptr,而不是之前。

另外:TCP是流协议;无法保证连接一端的write()将被另一端的单个recv()完全读取。