【问题标题】:how can we send a text file from client to the server?我们如何将文本文件从客户端发送到服务器?
【发布时间】:2013-10-15 09:38:54
【问题描述】:

我正在尝试使用 C 套接字编程将文件从客户端发送到服务器。但是在服务器端,我无法接收从客户端发送的文件。我附上下面的代码。

服务器:

/*  Create a connection queue and wait for clients.  */

listen(server_sockfd, 5);
while(1) {
    char ch;

    printf("server waiting\n");

/*  Accept a connection.  */

    client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd,(struct sockaddr*)&client_address,cli);
    if(client_sockfd > 0)
    printf("client is connected\n");
/*  We can now read/write to client on client_sockfd.  */
  char *fh;
    recv(client_sockfd,fh,1024+1,0);
    printf("server recieved %s",fh);

/*        read(client_sockfd, &ch, 1);
    ch++;
    write(client_sockfd, &ch, 1); */
   return close(client_sockfd);
}
}

【问题讨论】:

  • 这可能是关于 stackoverflow 的一个更好的问题。
  • 代码中有几个未定义的变量(例如filemessage)。请将此代码更新为至少可以编译的代码。
  • 'char *buffer[1024];' - 你真的想要一个包含 1024 个指针的数组吗?

标签: c sockets


【解决方案1】:

你需要检查recv的返回

if ((nbytes = recv(client_sockfd,fh,1024+1,0)) > 0)

并用'\0'结束你的缓冲区

fh[nbytes] = '\0';
printf("server recieved %s",fh);

另外,使用 1024+1 这样的幻数也不是一个好主意

【讨论】:

    猜你喜欢
    • 2015-05-02
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 2016-04-04
    相关资源
    最近更新 更多