前言
使用多线程不阻塞的方式,内置自动消息接收和发送的机制,完成对多个客户端连接的消息处理,保证数据处理及时和高量并发的效果
1.预览效果
2.核心程序
代码如下:
DWORD WINAPI cSocketServer::sendCmdDataThread(LPVOID lpParam)
{
cSocketServer *pMain = (cSocketServer*)lpParam;
int nStep = 0;
sUnChokeTimer timer[2];
int nReConnectTimes = 3 * 1000;
int nHeatTickTimes = 10 * 1000;
cSendInfo sendInfo;
while (true)
{
if (pMain->isRelease())
return 0;
else
QThread::msleep(5);
switch (nStep)
{
case 0:
{
if (!pMain->isStarted())
QThread::msleep(500);
else
nStep = 1;
}break;
case 1:
{
pMain->operaterClientSocketList(OP_SEND_DATA);
nStep = 2;
}break;
case 2:
{
pMain->operaterClientSocketList(OP_DEAL_DATA);
nStep = 3;
}break;
default:
nStep = 1;
break;
}
}
return 0;
}
DWORD WINAPI cSocketServer::recieveCmdDataThread(LPVOID lpParam)
{
cSocketServer *pMain = (cSocketServer*)lpParam;
SOCKET socketClient;
SOCKADDR_IN addrSrv;
SOCKADDR_IN addrClient;
int nSockeAddrSize = sizeof(SOCKADDR);
u_long ioMode = 1;
int nStep = 0;
while (true)
{
if (pMain->isRelease())
return 0;
else
QThread::msleep(5);
switch (nStep)
{
case 0:
{
if (!pMain->isStarted())
QThread::msleep(500);
else
nStep = 1;
}break;
case 1:
{
::ioctlsocket(pMain->d_ptr->socket, FIONBIO, (u_long FAR*)&ioMode);
::ioctlsocket(socketClient, FIONBIO, (u_long FAR*)&ioMode);
nStep = 2;
}break;
case 2:
{
socketClient = ::accept(pMain->d_ptr->socket, (sockaddr*)&addrClient, &nSockeAddrSize);
nStep = 3;
}break;
case 3:
{
if (socketClient != SOCKET_ERROR)
{
static int nId = 0;
QString strIp = QString("%1").arg(inet_ntoa(addrClient.sin_addr));
cSocketClient client;
client.setId(++nId);
client.setIp(strIp);
client.setSocket(socketClient);
pMain->operaterClientSocketList(OP_APPEND_CLIENT, &client);
emit pMain->sigSocketConnectAlive(client.Ip(), client.id(), true);
}
nStep = 4;
}break;
case 4:
{
pMain->operaterClientSocketList(OP_RECIEVE_DATA);
nStep = 5;
}break;
default:
nStep = 2;
break;
}
}
return 0;
}
3.程序下载
https://download.csdn.net/download/u013083044/21910682
|