MFC Socket 通信随笔
本MFC通信主要运用重载CSocket类中的方法,自定义消息等方法,简单创建发送文字消息的聊天软件。
头文件:
class MySocketServer : public CSocket
{
public:
void MySocketServer();//构造函数
~MySocketServer();//析构函数
virtual void OnSend(int iErrorCode);//发送消息的响应函数
virtual void OnAccept(int iErrorCode);//接收连接时的响应函数
virtual void OnReceive(int iErrorCode);//接收消息时的响应函数
virtual void OnClose(int iErrorCode);//关闭连接时的响应函数
void AttachWnd(CWnd* pWnd);//获取窗口句柄
private:
CWnd* pWnd;
};
cpp文件:
void MySocketServer::MySocketServer()
{
this->pWnd = NULL;
}
MySocketServer::~MySocketServer()
{
}
void MySocketServer::OnSend(int iErrorCode)
{
this->pWnd->SendMessage(WM_MYSOCKETMSG,0,SEND);//0对应响应函数的WPARAM参数,SEND对应LPARAM参数
CSocket::OnSend(iErrorCode);
}
void MySocketServer::OnAccept(int iErrorCode)
{
this->pWnd->SendMessage(WM_MYSOCKETMSG,0,ACCEPT);//自定义的消息响应事件
CSocket::OnAccept(iErrorCode);
}
void MySocketServer::OnReceive(int iErrorCode)
{
this->pWnd->SendMessage(WM_MYSOCKETMSG,0,RECEIVE);
CSocket::OnReceive(iErrorCode);
}
void MySocketServer::OnClose(int iErrorCode)
{
this->pWnd->SendMessage(WM_MYSOCKETMSG,0,CLOSE);
CSocket::OnClose(iErrorCode);
}
void AttachWnd(CWnd* pWnd)
{
this->pWnd = pWnd;
}
事件函数定义:
#define WM_MYSOCKETMSG (WM_USER+200)
afx_msg LRESULT SokcetMsg(WPARAM wParam,LPARAM lParam);//自定义响应函数
在相应需要响应事件的cpp中添加消息:
ON_MESSAGE(WM_MYSOCKETMSG,SocketMsg)
实现函数:
LRESULT MySocketTest::SoketMsg(WPARAM wParam,LPARAM lParam)
{
switch(lParam)
{
case SEND:
//发送消息时处理函数
break;
case ACCEPT:
//如果为服务器,接收连接时的处理函数
break;
case RECEIVE:
//接收消息时的处理函数
break;
case CLOSE:
//断开连接时的处理函数
break;
}
}
其中服务器即为接收连接的一方创建方式:
MySocketServer * pServerSocket = new MySocketServer();
pServerSocket->AttachWnd(this);
if(!pServerSocket->Create(MYPORT,SOCKT_STREAM)||!pServerSocket->Listen()) AfxMessageBox(_T(“创建服务器失败”));//SOCKET_STREAM为TCP连接方式,MYPORT为端口号
客户端:
MySocketServer * pClientSocket = new MySocketServer();
pClientSocket->AttachWnd(this);
if(!pClientSocket->Create()||!pCilenSocket->Connect(SERVER_IP_ADDRESS,SERVER_PORT)) AfxMessageBox(_T(“连接服务器失败”));
客户端获取消息:
char bBuff[1024];
ZeroMemory(bBuff,1024);
pClient->Receive(bBuff,1024);
CString strMsg = “”;
strMsg.Format(_T("%s"),bBuff);
服务器接收消息:
1、首先服务器需要接收连接(TCP机制)
MySocketServer * pConnectSocket = new MySocketServer();
pServerSocket->Accept((*pConnectSocket));
2、通过连接的Socket接收消息
pConnectSocket->Receive(bBuff,1024);
客户端服务器发送消息:
pConnectSocket->Send(strMsg,(strMsg.GetLength())*sizeof(TCHAR));//服务器
pClientSocket->Send(strMsg,(strMsg.GetLength())*sizeof(TCHAR));//客户端