2010-03-12 54 views
0
void CApplication::SendData(const char pBuffer[]) 
{ 
    if(pBuffer == NULL) 
    { 
     Log()->Write(ELogMessageType_ERROR, "Cannot send NULL message."); 
     return; 
    } 
    // calculate the size of that data 
    unsigned long messageSize = strlen(pBuffer); 

    // fix our byte ordering 
    messageSize = htonl(messageSize); 

    if(isServer == true) 
    { 
     for(unsigned int i = ESocket_CLIENT0; i < ESocket_MAX; ++i) 
     { 
      // send the message size 
      if(m_Socket[ i ] > 0) 
      { 
       if(send(m_Socket[ i ], (char*)&messageSize, sizeof(messageSize), 0) == SOCKET_ERROR) 
       { 
        Log()->Write(ELogMessageType_ERROR, "[Application] Send error: %i to socket %i", WSAGetLastError(), m_Socket[ i ]); 
        continue; 
       } 

       // fix our message size back to host ordering 
       messageSize = ntohl(messageSize); 

       // send the actual message 
       if(send(m_Socket[ i ], pBuffer, messageSize, 0) == SOCKET_ERROR) 
       { 
        Log()->Write(ELogMessageType_ERROR, "[Application] Send error: %i to socket %i", WSAGetLastError(), m_Socket[ i ]); 
        continue; 
       } 

       Log()->Write(ELogMessageType_MESSAGE, "[Application] SEND: %s", pBuffer); 
      } 
     } 
    } 
+1

2件事情可能會阻止發送而不記錄它:你的isServer標誌是錯誤的,你所有的m_Socket都是0,沒有辦法從這裏檢查這個。 – stefaanv 2010-03-12 08:29:59

+1

你正在做循環中的ntohl。這將對小端系統產生不利影響。 – stefaanv 2010-03-12 08:31:01

回答

1

你沒有處理的情況下,send()發送的數據少於你所要求的。如果情況確實如此,則需要循環,直到所有數據都消失。如果客戶端斷開連接,您也不會處理錯誤,例如send()可能會返回-1。

典型的方法是一樣的東西::

for(size_t to_go = messageSize; to_go > 0;) 
{ 
    int put = send(sock, buf, to_go); 
    if(put < 0) 
    { 
    perror("Socket send() error"); 
    break; 
    } 
    buf += put; 
    to_go -= put; 
} 

這種嘗試發送全部剩餘消息,直到所有已發送。你當然需要適應你的特定變量名稱,做更好的錯誤處理,等等。請將上面的內容作爲草圖進行查看。

+0

你認爲我應該如何解決這個問題? – user292188 2010-03-12 09:00:02

+0

非常感謝你:) – user292188 2010-03-12 09:54:34

+0

@crsin:隨時接受答案,如果你覺得它幫助了你。 :) – unwind 2010-03-12 10:01:48

相關問題