Client.cpp
上传用户:bsw_2008
上传日期:2013-07-09
资源大小:2446k
文件大小:2k
- // Client.cpp: implementation of the CClient class.
- //
- //////////////////////////////////////////////////////////////////////
- #include "stdafx.h"
- #include "CGameHallFrame.h"
- #include "Client.h"
- #include "CGameHallFrameView.h"
- #ifdef _DEBUG
- #undef THIS_FILE
- static char THIS_FILE[]=__FILE__;
- #define new DEBUG_NEW
- #endif
- //////////////////////////////////////////////////////////////////////
- // Construction/Destruction
- //////////////////////////////////////////////////////////////////////
- CClient::CClient()
- {
- m_hSocket=NULL;
- }
- CClient::~CClient()
- {
- }
- void CClient::ClientInit()
- {
- if(WSAAsyncSelect(m_hSocket,m_hWnd,CLI_MESSAGE,FD_READ|FD_WRITE|FD_CLOSE|FD_CONNECT)>0)
- {
- AfxMessageBox("Error in select");
- }
- }
- BOOL CClient::InitAndConnect(HWND hWnd, UINT port, CString strServer)
- {
- m_hWnd=hWnd;
- m_uPort=port;
- m_strServer=strServer;
- if(m_hSocket!=NULL)
- {
- //先将以前打开的套接字关闭
- closesocket(m_hSocket);
- m_hSocket=NULL;
- }
- //创建面向连接的socket
- m_hSocket=socket(AF_INET,SOCK_STREAM,0);
- ASSERT(m_hSocket!=NULL);
- ClientInit();
- //设置连接信息:网络协议+IP地址+端口
- m_addr.sin_family=AF_INET;
- m_addr.sin_addr.S_un.S_addr=inet_addr(m_strServer.GetBuffer(0));
- m_addr.sin_port=htons(m_uPort);
- //连接服务器
- int ret=0;
- int error=0;
- ret=connect(m_hSocket,(LPSOCKADDR)&m_addr,sizeof(m_addr));
- if(ret==SOCKET_ERROR)
- {
- //连接失败
- if(GetLastError()!=WSAEWOULDBLOCK)
- {
- AfxMessageBox(_T("请确认服务器确实已经打开并工作在同样的端口!"));
- return FALSE;
- }
- }
- return TRUE;
- }
- void CClient::GetString(CString &str)
- {
- recv(m_hSocket,str.GetBuffer(0),1024,MSG_DONTROUTE);
- }
- void CClient::SendString(CString a)
- {
- if(send(m_hSocket,a.GetBuffer(0),a.GetLength(),0)==SOCKET_ERROR)
- {
- AfxMessageBox("Client Send data error");
- }
- }