通过winsock / linux套接字发送文件

时间:2011-04-03 20:44:46

标签: c

嘿,我正在创建一个发送/接收文件的简单程序,我的代码发送文本文件但是当涉及到二进制时它开始出错,代码:

static void
send_event(conn,file)
  void *conn;
  void *file;
{
   FILE *f;
   char *buffer;
   int32_t block_size;
   int32_t size;
   size_t __read;
   ConnectionQueue *q;
   f = (FILE *)file;
   q = (ConnectionQueue *)conn;
   block_size = conf_getint("transfer:block_size");
   if (block_size <= 1 || block_size > 1024)
     {
       abort();
       return;
     }
   buffer = (char *)MyMalloc(block_size);
   if (!q || !f)
     return;

   fseek(f,0L,SEEK_END);
   size = ftell(f);
   if (size == 0L)
     {
       send_socket(q->conn,"RECEIVE: 302 FSE");
       return;
    }
   fseek(f,0,SEEK_SET);
   while (true)
    {
      if (q->abort)
       {
         send_socket(q->conn,"RECEIVE: File transfer aborted\n");
         if (f)
           fclose(f);
         f = NULL;
         MyFree(buffer);
         return;
       }
      __sleep(100);
       __read = fread(buffer,sizeof(char),512,f);
       if (__read <= 0)
         {
           send_socket(q->conn,"RECEIVE: EOF\n");
           break;
         }
      if (*buffer == '\0')
        {
          send_socket(q->conn,"RECEIVE: EOF\n");
          break;
        }

      send_socket(q->conn,"RECEIVE: %s\n",buffer);
   }
   send_socket(q->conn,"RECEIVE: 915 EOF\n");
   fclose(f);
   f = NULL;
   MyFree(buffer);
}

固定:请检查我的回答\ /

2 个答案:

答案 0 :(得分:2)

K&amp; R语法和void *参数有什么用?

static void send_event( ConnectionQueue * conn, FILE * file) {
....

在二进制文本与文本上,通常这是因为您使用“r”而不是“rb”作为模式打开文件。

 __read = fread(buffer,sizeof(char),512,f);

您应该使用block_size而不是512

if (*buffer == '\0')
...
send_socket(q->conn,"RECEIVE: %s\n",buffer);

你的“二进制文件”可能包含0 - 这不是一个好的EOF标记,如果你在strlen中使用send_socket,你的数据会在你的第一个0处被截断缓冲液中。

答案 1 :(得分:0)