You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.4 KiB
C++

#include "StdAfx.h"
#include "SocketMgr.h"
#include "LogMgr.h"
#include <Winsock2.h>
#pragma comment(lib, "ws2_32.lib")
CSocketMgr *gSocketMgr = new CSocketMgr;
CSocketMgr::CSocketMgr(void)
{
}
CSocketMgr::~CSocketMgr(void)
{
}
//通讯初始化
void CSocketMgr::OnAppInitialize()
{
//初始化套接字socket
if(!AfxSocketInit())
{
gLogMgr->WriteDebugLog("Err---->CSocketMgr : AfxSocketInit : Err");
}
else
{
gLogMgr->WriteDebugLog("Func---->CSocketMgr : AfxSocketInit : OK");
}
}
//建立Socket 连接S_addr:连接的IP 地址,port:端口号
bool CSocketMgr::Connect(const char* S_addr,u_short port)
{
m_Socket.Create();
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr(S_addr);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(port);
if(m_Socket.Connect((SOCKADDR*)&addrSrv,sizeof(SOCKADDR)))
{
gLogMgr->WriteDebugLog("Socket 连接成功");
return true;
}
else
{
gLogMgr->WriteDebugLog("Socket 连接失败",_LOG_ERROR);
Close();
return false;
}
}
//关闭socket 连接
void CSocketMgr::Close()
{
gLogMgr->WriteDebugLog("Socket 关闭");
m_Socket.Close();
}
//socket 向服务器端发送数据
void CSocketMgr::Send(char* lpBuf,int nBufLen)
{
m_Socket.Send(lpBuf,nBufLen,0);
}
//socket 从服务器端接收数据
void CSocketMgr::Receive(char* lpBuf,int nBufLen)
{
m_Socket.Receive(lpBuf,nBufLen,0);
}