本代码服务端引用了http://www.codeproject.com/KB/IP/IOCP_how_to_cook.aspx中的代码,并作了少量修改,在这里对原作者表示感谢。。
功能描述:
* 封装了心跳机制
* 封装了一层应用层协议,支持压缩传输
* Client端封装了掉线重连机制
示例代码演示了文件传输并输出传输速度
希望朋友们能不吝指教,帮助我进步 :)
点击下载源码
服务端:
class CMyTcpServer : public CFTcpServer
{
public:
CMyTcpServer();
virtual ~CMyTcpServer();
virtual BOOL OnReadF(SCSocket *pSocket, PBYTE pData, DWORD dwLen)
{
static DWORD btCount = 0;
static DWORD dwTime = GetTickCount();
static DWORD lastTime = dwTime;
btCount += dwLen;
HANDLE hFile = CreateFile("c:\\abc.dat", GENERIC_WRITE, FILE_SHARE_WRITE,
NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
SetFilePointer(hFile, 0, 0, FILE_END);
DWORD dwBytesWrite = 0;
WriteFile(hFile, pData, dwLen, &dwBytesWrite, NULL);
CloseHandle(hFile);
DWORD dwTTT = GetTickCount();
if (dwTTT - lastTime > 1000)
{
lastTime = dwTTT;
printf("%dkb/s %u\n", (int)(((double)btCount) * 1000 / (dwTTT - dwTime) / 1024), btCount);
}
return TRUE;
}
virtual int OnConnected(SCSocket *pSocket){return TRUE};
};
int main(int argc, char* argv[])
{
CMyTcpServer::InitSocketLib();
CMyTcpServer ts;
ts.Start(9908, 5000, 8, 150000);
while( !_kbhit() ) ::Sleep(100);
ts.Stop();
return 0;
}
客户端:
class CMyTcpClient : public CFTcpClient
{
public:
CMyTcpClient();
virtual ~CMyTcpClient();
virtual VOID OnConnected()
{
char buff[BUFF_SIZE_C - 100];
HANDLE hFile;
hFile = CreateFile("c:\\abc.dat", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
DWORD nNumberOfBytesRead = 0;
int pos = 0;
while (ReadFile(hFile, buff, BUFF_SIZE_C - 100, &nNumberOfBytesRead, NULL))
{
if (BUFF_SIZE_C - 100 == nNumberOfBytesRead)
Send(buff, nNumberOfBytesRead);
else
break;
}
CloseHandle(hFile);
Send(buff, nNumberOfBytesRead, TRUE);
};
virtual int OnReadF(LPSTR pData, int nSize)
{
return TRUE;
}
};
int main(int argc, char* argv[])
{
CMyTcpClient::InitSocketLib();
CMyTcpClient *pcl = new CMyTcpClient;
pcl->Start("192.168.1.138", 9908);
while( !_kbhit() ) ::Sleep(100);
return 0;
}