2013-04-06 71 views
2

我与一些C++插座实例的工作将文件发送。客户端运行并可以连接到服务器,但无法发送文件。我认为send()有问题,但我无法修复它。编辑:错误消息是“连接重置对等”未能通过插座

欢迎任何想法。

我用的OpenSuSE与QT 4.7.4

这里的发送和接收功能

void str_server(int sock) 
{ 
    char buf[1025]; 
    const char* filename = "//home//romanov//Documents//HelloWorld-build-desktop-Qt_4_7_4_in_PATH__System__Release//ss.png"; 

    FILE *file = fopen(filename, "rb"); 
    if (!file) 
    { 

     cerr<<"Can't open file for reading"; 
     return; 
    } 
    while (!feof(file)) 
    { 
     int rval = fread(buf, 1, sizeof(buf), file);//read value 
     if (rval < 1) 
     { 

      cerr<<"Can't read from file"; 
      fclose(file); 
      return; 
     } 

     int off = 0; 
     do 
     { 
      int sent = send(sock, &buf[off], rval - off, 0); 
      if (sent < 1) 
      { 
       // if the socket is non-blocking, then check 
       // the socket error for WSAEWOULDBLOCK/EAGAIN 
       // (depending on platform) and if true then 
       // use select() to wait for a small period of 
       // time to see if the socket becomes writable 
       // again before failing the transfer... 

       cout<<"Can't write to socket"; 
       fclose(file); 
       return; 
      } 

      off += sent; 
     } 
     while (off < rval); 
    } 

    fclose(file); 
} 

// ===================

void RecvFile(int winsock) 
{ 
    int rval; 
    char buf[1025]; 
    FILE *file = fopen("//home//romanov//Documents//HelloWorld-build-desktop-Qt_4_7_4_in_PATH__System__Release//ss2.png", "wb"); 
    if (!file) 
    { 
     printf("Can't open file for writing"); 
     return; 
    } 

    do 
    { 
     rval = recv(winsock, buf, sizeof(buf), 0); 
     if (rval < 0) 
     { 
      // if the socket is non-blocking, then check 
      // the socket error for WSAEWOULDBLOCK/EAGAIN 
      // (depending on platform) and if true then 
      // use select() to wait for a small period of 
      // time to see if the socket becomes readable 
      // again before failing the transfer... 

      printf("Can't read from socket"); 
      fclose(file); 
      return; 
     } 

     if (rval == 0) 
      break; //line 159 

     int off = 0; 
     do 
     { 
      int written = fwrite(&buf[off], 1, rval - off, file); 
      if (written < 1) 
      { 
       printf("Can't write to file"); 
       fclose(file); 
       return; 
      } 

      off += written; 
     } 
     while (off < rval); 
    } //line 175 
    while (1); 
    fclose(file); 
} 
+1

没有必要在你的字符串中的“/”字符的两倍。 '\\'出现在Windows上,因为'\'是一个转义字符,为了得到一个文字'\',你必须将它们中的两个连在一起。 – Omnifarious 2013-04-06 22:56:11

+0

它如何失败?它是否打印出任何消息?这是你应该使用'cerr'而不是'cout'的情况。 – Omnifarious 2013-04-06 22:59:02

+0

谢谢你指出。 输出为“无法从套接字写入”。所以我想''send()'有问题。我现在编辑的问题,是我不好:( – Tiana987642 2013-04-06 23:04:27

回答