Socket 物件 Part 2
延續上一篇 Socket 物件 Part 1
我們將在這邊說明這個Socket使用的範例
Socket的初始化
int main(int argc, char **argv) { Net::Initial(); Net::Socket _socket; _socket.Create(AF_INET, SOCK_STREAM, IPPROTO_TCP ); _socket.Connect(AF_INET,"127.0.0.1", 18000); // other work and so on.... Net::Terminate(); return 0; }
Socket操作實發生異常的處理方式
try { std::string _szSend("Send test"); _socket.Send(_szSend.c_str(), _szSend.size(), 0); } catch(Net::SocketException sockExp) { std::cout << sockExp.no() << std::endl; std::cout << sockExp.what() << std::endl; } catch(std::exception exp) { std::cout << exp.what() << std::endl; } catch(const char* errorMsg) { std::cout << errorMsg << std::endl; }
從網路卡的buffer讀取資料的做法
bool RecvFromBuff(Net::Socket& socket, std::string& szData) { if( !socket.Select(0)) return false; int _dataSizeInBuff = socket.ReceivedBuffSize(); if(_dataSizeInBuff==0) return false; Net::DataBlock _dataBlock(_dataSizeInBuff); socket.Recv(_dataBlock, _dataSizeInBuff, 0); szData.append(_dataBlock, _dataSizeInBuff); return true; }