异步 (非阻塞) 客户端 Socket 封装类(无需MFC)

[图片] 示例程序截图

异步 (非阻塞) 客户端 Socket 封装类(无需MFC)_第1张图片

[代码] 使用方法

view source
print ?
01 #include "XSocket.h"
02  
03  
04   
05 ....
06   
07 CXSocket mySock;
08  
09 if (!mySock.Init()) //initalize winsocks
10     return false;
11       
12 //////////////////////////////////////////////////////////////////////////
13       
14 if (!mySock.Connect(pHostName, nPort))
15 {
16     int nError = mySock.GetLastError();
17     return false;
18 }
19   
20 /////////////////////////////////////////////////////////////////////////
21   
22 // Send a buffer, 5 seconds timeout
23 // further error checking omitted for previty
24   
25 int nLen = 0;
26 if (mySock.Send(szBuff, strlen(szBuff), nLen, 5000) != E_XSOCKET_SUCCESS)
27     return false;
28      
29  
30 /////////////////////////////////////////////////////////////////////////
31   
32 // Receive server's response, 5 seconds time out
33 // last argument is optional, if not used Rec will return immediately
34   
35 do
36 {
37     if (mySock.Recv(szBuff, sizeof(szBuff) - 1, nLen, 5000) 
38         != E_XSOCKET_SUCCESS)
39     {
40     break;
41     }
42 }
43     while (nLen == sizeof(szBuff)); 
44   
45   
46 //////////////////////////////////////////////////////////////////////////
47   
48 // Optional: explicitly close the socket, if not called socket will be closed
49 // auto on destruction
50   
51 mySock.Close();

你可能感兴趣的:(异步 (非阻塞) 客户端 Socket 封装类(无需MFC))