TCP.cpp
上传用户:hnzycx
上传日期:2022-08-09
资源大小:12567k
文件大小:3k
- #include "StdAfx.h"
- #include "TCP.h"
- CTCP::CTCP(void)
- {
- //初始化socket环境
- WSADATA wsd;
- WSAStartup(MAKEWORD(1,1),&wsd);
- //创建线程退出事件句柄
- m_exitThreadEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
- }
- CTCP::~CTCP(void)
- {
- //释放socket资源
- WSACleanup();
- //关闭线程退出事件句柄
- CloseHandle(m_exitThreadEvent);
- }
- //此线程用于监视客户端通讯的事件
- DWORD CTCP::SocketThreadFunc(LPVOID lparam)
- {
- CTCP *pSocket;
- pSocket = (CTCP*)lparam;
- fd_set fdRead;
- int ret;
- TIMEVAL aTime;
- aTime.tv_sec = 1;
- aTime.tv_usec = 0;
- while (TRUE)
- {
- if (WaitForSingleObject(pSocket->m_exitThreadEvent,0) == WAIT_OBJECT_0)
- {
- break;
- }
- FD_ZERO(&fdRead);
- FD_SET(pSocket->m_socket,&fdRead);
- ret = select (0,&fdRead,NULL,NULL,&aTime);
- if (ret == SOCKET_ERROR)
- {
- pSocket->OnError(pSocket->m_pOwnerWnd,1);
- pSocket->OnDisConnect(pSocket->m_pOwnerWnd);
- closesocket(pSocket->m_socket);
- break;
- }
- if (ret>0)
- {
- if (FD_ISSET(pSocket->m_socket,&fdRead))
- {
- char recvBuf[1024];
- int recvLen;
- ZeroMemory(recvBuf,1024);
- recvLen = recv(pSocket->m_socket,recvBuf,1024,0);
- if (recvLen == SOCKET_ERROR)
- {
- int Ierror = WSAGetLastError();
- pSocket->OnError(pSocket->m_pOwnerWnd,Ierror);
- pSocket->OnDisConnect(pSocket->m_pOwnerWnd);
- closesocket(pSocket->m_socket);
- break;
- }
- else if (recvLen == 0)
- {
- pSocket->OnDisConnect(pSocket->m_pOwnerWnd);
- closesocket(pSocket->m_socket);
- }
- else
- {
-
- pSocket->OnRead(pSocket->m_pOwnerWnd,recvBuf,recvLen);
- }
- }
- }
- }
- return 0;
- }
- //打开客户端socket
- bool CTCP::Open(CWnd *pWnd)
- {
- //复位线程退出事件
- ResetEvent(m_exitThreadEvent);
- //存储父窗口句柄
- m_pOwnerWnd = pWnd;
- //创建tcp套接字
- m_socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
- if (m_socket == SOCKET_ERROR)
- {
- return FALSE;
- }
- //创建通讯线程
- tcpThreadHandle = CreateThread(NULL,0,SocketThreadFunc,this,0,NULL);
- if (tcpThreadHandle == NULL)
- {
- closesocket(m_socket);
- return FALSE;
- }
- return TRUE;
- }
- //关闭客户端socket
- bool CTCP::Close()
- {
- //发送线程退出事件
- SetEvent(m_exitThreadEvent);
- Sleep(1000);
- //关闭socket,释放资源
- int err = closesocket(m_socket);
- if (err == SOCKET_ERROR)
- {
- return FALSE;
- }
- return TRUE;
- }
- //建立与服务器的连接
- bool CTCP::Connect()
- {
- struct sockaddr_in addr;
- int err;
- addr.sin_family = AF_INET;
- addr.sin_port = htons(m_port);
- //此处要将双字节转换成单字节
- char ansiRemoteHost[255];
- ZeroMemory(ansiRemoteHost,255);
- WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,m_remoteHost,wcslen(m_remoteHost),ansiRemoteHost,wcslen(m_remoteHost),NULL,NULL);
- addr.sin_addr.s_addr = inet_addr(ansiRemoteHost);
- //此时采用同步连接方式,connect直接返回成功或是失败
- err = connect(m_socket,(struct sockaddr *)&addr,sizeof(addr));
- if (err == SOCKET_ERROR)
- {
- return FALSE;
-
- }
- //设置通讯模式为异步模式
- DWORD ul = 1;
- ioctlsocket(m_socket,FIONBIO,&ul);
- return TRUE;
- }
- //向服务器发送数据
- bool CTCP::SendData(const char *buf, int len)
- {
- send(m_socket,buf,len,0);
- return TRUE;
- }