2014-10-31 78 views
1

我想使用boost :: asio :: ip :: tcp :: socket的方法「read_some()」來填充表示爲char * 。將char *轉換爲boost :: array for socket使用

這裏是我的方法實現迄今:

template<class charType> 
int receive_some(charType* buffer, int size) 
{ 
    int total_received = 0; 

    boost::array<charType, size> buf; 
    while (1) 
    { 
     int received = 0; 
     boost::system::error_code error; 
     received = _socket.read_some(boost::asio::buffer(buf), error); 
     if (error == boost::asio::error::eof) 
     { 
      break; 
     } 
     std::cout.write(buf.data(), received); 
     total_received += received; 
     } 

    return total_received; 

} 

我的問題是我不知道如何轉換我的charType *緩衝區中的boost ::數組buf中。在進程結束時迭代我的boost :: array的元素以填充緩衝區對象似乎很昂貴...

任何想法?

+0

爲什麼模板化?你希望從網絡中接收其他字節嗎? – Eric 2014-10-31 09:05:49

+1

也許他從插座接受蔬菜......在這種情況下,它必須是一個模板。但是,在這裏不需要模板。 – Blacktempel 2014-10-31 09:09:44

+0

我可以接收char *,unsigned char *等,不是? – 2014-10-31 10:03:53

回答

4
template<class charType> 
int receive_some(charType* buffer, int size) 
{ 
    int total_received = 0; 

    while (1) 
    { 
     int received = 0; 
     boost::system::error_code error; 
     received = _socket.read_some(boost::asio::buffer(buffer, size), error); 
     if (error == boost::asio::error::eof) 
     { 
      break; 
     } 
     std::cout.write(buffer, received); 
     total_received += received; 
     } 

    return total_received; 

} 

boost::asio::buffer該功能有很多重載以允許創建從不同勢類型的源的緩衝器ASIO。

值得注意的是,size必須是要讀入buffer的字節數,而不是charType的數字。

獎勵提示:正如評論指出的那樣,該模板是可疑的,你可以用它做的最好的是直接寫入寬字符串,但這可能比在read_some函數中更好(實際上它甚至可能更好),在處理字節而不是字符的網絡函數中,所以您最好採用簡單的char*甚至void*作爲buffer參數的類型。

+1

謝謝!工作:)並感謝您的額外提示 – 2014-10-31 10:05:15