#pragma once
#include "pch.h"
#include "framework.h"
//单例模式
class CServerSocket
{
public:
static CServerSocket* getInstance()
{
if(m_instance == nullptr)
{
m_instance = new CServerSocket();
}
return m_instance;
}
bool InitSocket()
{
if (m_sock == -1) return false;
sockaddr_in serv_adr;
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.S_un.S_addr = INADDR_ANY;
serv_adr.sin_port = htons(8888);
//绑定
if (bind(m_sock, (sockaddr*)&serv_adr, sizeof(sockaddr_in) == -1)) return false;
//TODO: 返回值
if( listen(m_sock, 1) == -1) return false;
return true;
}
bool AcceptClient()
{
sockaddr_in client_adr;
int cli_sz = sizeof(client_adr);
m_client = accept(m_sock, (sockaddr*)&client_adr, &cli_sz);
if (m_client == -1) return false;
return true;
}
int DealCommand()
{
char buffer[1024];
while(true)
{
int len = recv(m_client, buffer, sizeof(buffer), 0);
if(len <= 0 )
{
return -1;
}
//TODO: 处理命令
}
}
bool Send(const char* pData,size_t nSize)
{
return send(m_client, pData, nSize, 0) > 0;
}
CServerSocket& operator=(const CServerSocket& ss) = delete;
CServerSocket(const CServerSocket&) = delete;
private:
SOCKET m_sock;
SOCKET m_client;
CServerSocket():m_client(INVALID_SOCKET)
{
if(InitSockEnv() == FALSE)
{
MessageBox(NULL, _T("无法初始化套接字环境,请检查网络设置"), _T("初始化错误"), MB_OK | MB_ICONERROR);
exit(0);
}
m_sock = socket(PF_INET, SOCK_STREAM, 0);
};
~CServerSocket()
{
closesocket(m_sock);
WSACleanup();
};
BOOL InitSockEnv()
{
WSADATA data;
if(WSAStartup(MAKEWORD(1, 1), &data) != 0)
{
return FALSE;
}
return TRUE;
//TODO: 返回值处理
}
static CServerSocket* m_instance;
static void releaseInstance()
{
if(m_instance != NULL)
{
CServerSocket* tmp = m_instance;
m_instance = NULL;
delete tmp;
}
}
class CHelper
{
public:
CHelper()
{
CServerSocket::getInstance();
}
~CHelper()
{
CServerSocket::releaseInstance();
}
};
static CHelper m_helper;
};
extern CServerSocket server;
#include "pch.h"
#include "ServerSocket.h"
CServerSocket* CServerSocket::m_instance = NULL;
CServerSocket::CHelper CServerSocket::m_helper;
CServerSocket* pserver = CServerSocket::getInstance();
能解释一下CHelper类的意义吗 和调用原理吗