2013-04-06 68 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

回答