1.阻塞模式
会造成线程阻塞的有下列四种操作:
(1) 接受连接请求:accept()
(2) 接受数据:recv(),recvfrom()
(3) 请求连接:connect()
(4) 发送数据:send(),sendto()
其中1、2最容易发生阻塞。
2、多线程的阻塞模式
class CServerDlg : public CDialog
{
SOCKET m_ClientSock;
SOCKET m_ServerSock;
HANDLE m_RecvThread;
HANDLE m_AcceptThread;
.
friend DWORD WINAPI RecvThreadPro(LPVOID LpP);
friend DWORD WINAPI AcceptThreadPro(LPVOID LpP);
};
//创建线程
BOOL CServerDlg::OnInitDialog()
{
//创建线程
DWORD ThreadID;
m_RecvThread = CreateThread(NULL, 0, RecvThreadPro, this, CREATE_SUSPENDED, &ThreadID);
m_AcceptThread = CreateThread(NULL, 0, AcceptThreadPro, this, CREATE_SUSPENDED, &ThreadID);
int Count = ResumeThread(m_AcceptThread);
}
//接收数据线程
DWORD WINAPI RecvThreadPro(LPVOID LpP)
{
CServerDlg *pServer = (CServerDlg *)LpP;
ZeroMemory(buf, 20);
int nLen = recv(pServer->m_ClientSock, buf, 20, 0);
if(SOCKET_ERROR == nLen)
AfxMessageBox("Recv Failed!");
else
AfxMessageBox(buf);
return 0;
}
//接受客户端请求线程
DWORD WINAPI AcceptThreadPro(LPVOID LpP)
{
CServerDlg *pServer = (CServerDlg *)LpP;
struct sockaddr ClientAddr;
int len = sizeof(SOCKADDR_IN);
pServer->m_ClientSock = accept(pServer->m_ServerSock, &ClientAddr, &len);
if(SOCKET_ERROR == pServer->m_ClientSock)
AfxMessageBox("Accept Failed!");
return 0;
}
//结束线程
void CServerDlg::OnClose()
{
// TODO: Add your message handler code here and/or call default
//结束AcceptThread
DWORD ThreadState;
GetExitCodeThread(m_AcceptThread, &ThreadState);
if(ThreadState == STILL_ACTIVE)
{
//TerminateThread(m_hThread, 0);
WaitForSingleObject(m_AcceptThread,0xffffffff);
CloseHandle(m_AcceptThread);
}
//结束RecvThread
GetExitCodeThread(m_RecvThread, &ThreadState);
if(ThreadState == STILL_ACTIVE)
{
//TerminateThread(m_RecvThread, 0);
WaitForSingleObject(m_RecvThread,0xffffffff);
CloseHandle(m_RecvThread);
}
CDialog::OnClose();
}
posted on 2009-07-26 11:09
yunboy 阅读(514)
评论(0) 编辑 收藏 引用 所属分类:
网络通信