www.pudn.com > tcpS.rar > MySock.cpp


// MySock.cpp: implementation of the MySock class. 
// 
////////////////////////////////////////////////////////////////////// 
 
#include "stdafx.h" 
#include "tcpS.h" 
#include "MySock.h" 
#include "tcpSDlg.h" 
#ifdef _DEBUG 
#undef THIS_FILE 
static char THIS_FILE[]=__FILE__; 
#define new DEBUG_NEW 
#endif 
 
////////////////////////////////////////////////////////////////////// 
// Construction/Destruction 
////////////////////////////////////////////////////////////////////// 
 
MySock::MySock() 
{ 
 
} 
 
MySock::~MySock() 
{ 
 
} 
DWORD WINAPI SelectThread(void *pVoid) 
{ 
	CTcpSDlg *pTcpSDlg = (CTcpSDlg*)pVoid; 
	int errorcode; 
	 
	fd_set readfds; 
	 
	timeval timeout; 
	char    Buffer[1024]; 
	timeout.tv_sec = 0; 
	timeout.tv_usec = 500000; 
	u_long ul = 1;//非阻塞为非0 阻塞为0 
	errorcode = ioctlsocket(pTcpSDlg->m_MySock.m_ClieSocket,FIONBIO,&ul); 
	if (0 == errorcode) 
	{ 
	} 
	else if (SOCKET_ERROR == errorcode) 
	{ 
		errorcode = WSAGetLastError(); 
	} 
	while(pTcpSDlg->b_run) 
	{	 
		FD_ZERO(&readfds); 
		FD_SET(pTcpSDlg->m_MySock.m_ClieSocket,&readfds); 
		 
		errorcode = select(pTcpSDlg->m_MySock.m_ClieSocket+1,&readfds,NULL,NULL,&timeout); 
		if(errorcode == SOCKET_ERROR) 
		{ 
			//			MessageBox("select failed!"); 
			//WSACleanup(); 
			errorcode = WSAGetLastError(); 
			 
			return -1; 
		} 
		//timeout 
		else if(errorcode == 0) 
		{ 
			//MessageBox("time out!"); 
			continue; 
		} 
		else 
		{ 
			if(FD_ISSET(pTcpSDlg->m_MySock.m_ClieSocket,&readfds)) 
			{ 
				ZeroMemory(Buffer,1024); 
				errorcode = recv(pTcpSDlg->m_MySock.m_ClieSocket,Buffer,1024,0); 
				Buffer[errorcode] = '\0'; 
				if(errorcode == SOCKET_ERROR) 
				{ 
					return -1; 
				} 
				//接受后的处理 
				else if(errorcode == 0) 
				{ 
					//已经断开 
					//					closesocket(pTcpServerDlg->m_MySock.m_ClieSocket); 
					pTcpSDlg->m_strMsg = "the client is close!"; 
					::PostMessage(pTcpSDlg->m_hWnd,WM_MYMSG,0,0); 
					continue; 
				} 
				else 
				{ 
					CString s; 
					s.Format("%s",Buffer); 
					pTcpSDlg->m_strMsg = s; 
					::PostMessage(pTcpSDlg->m_hWnd,WM_MYMSG,0,0); 
				} 
			} 
		} 
	} 
	return 0; 
}