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

来源:互联网 发布:plc的编程语言有哪些 编辑:程序博客网 时间:2024/06/14 10:11

[图片] 示例程序截图

[代码] 使用方法

view source
print?
01#include "XSocket.h"
02 
03 
04  
05....
06  
07CXSocket mySock;
08 
09if (!mySock.Init()) //initalize winsocks
10    returnfalse;
11      
12//////////////////////////////////////////////////////////////////////////
13      
14if (!mySock.Connect(pHostName, nPort))
15{
16    intnError = mySock.GetLastError();
17    returnfalse;
18}
19  
20/////////////////////////////////////////////////////////////////////////
21  
22// Send a buffer, 5 seconds timeout
23// further error checking omitted for previty
24  
25int nLen = 0;
26if (mySock.Send(szBuff, strlen(szBuff), nLen, 5000) != E_XSOCKET_SUCCESS)
27    returnfalse;
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  
35do
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  
51mySock.Close();
原创粉丝点击