MFC Socket通信随笔

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));//客户端

声明:借鉴学习 https://www.cnblogs.com/ht-beyond/p/4529436.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值