c++ mfc tcp server

1 New mfc dialog box project ServerDemo

2 Create a new class CClientSocket in the class view as a socket for the server to receive data

#pragma once
#include <afxsock.h>
class CClientSocket :
    public CSocket
{

public:
    virtual void OnReceive(int nErrorCode);
};

#include "pch.h"
#include "CClientSocket.h"
#include "ServerDemo.h"


void CClientSocket::OnReceive(int nErrorCode)
{
	// TODO: 在此添加专用代码和/或调用基类
	char bufferData[2048];
	int len = Receive(bufferData, 2048);
	bufferData[len] = '\0';
	theApp.m_serverSock.SendAll(bufferData, len);

	CSocket::OnReceive(nErrorCode);
}

 

3 Create a new class CServerSocket in the class view and let it inherit from CSocket

#pragma once
#include "afxsock.h"
class CServerSocket :
    public CSocket
{
public:
    ~CServerSocket();
public:
    CPtrList m_socketList;
public:
    virtual void OnAccept(int nErrorCode);
    void SendAll(char* bufferData, int len);
    void DelAll();
};

#include "pch.h"
#include "CServerSocket.h"
#include "CClientSocket.h"


CServerSocket::~CServerSocket()
{
	DelAll();
}

void CServerSocket::OnAccept(int nErrorCode)
{
	// TODO: 在此添加专用代码和/或调用基类
	CClientSocket* pSocket = new CClientSocket();
	if (Accept(*pSocket))
	{
		m_socketList.AddTail(pSocket);
	}
	else
	{
		delete pSocket;
	}

	CSocket::OnAccept(nErrorCode);
}

void CServerSocket::SendAll(char* bufferData, int len)
{
	if (len!=-1)
	{
		bufferData[len] = 0;
		POSITION pos = m_socketList.GetHeadPosition();
		while (pos != NULL)
		{
			CClientSocket* socket = (CClientSocket*)m_socketList.GetNext(pos);
			if (socket!=NULL)
			{
				socket->Send(bufferData, len);
			}
		}
	}
}

void CServerSocket::DelAll()
{
	POSITION pos = m_socketList.GetHeadPosition();
	while (pos != NULL)
	{
		CClientSocket* socket = (CClientSocket*)m_socketList.GetNext(pos);
		if (socket != NULL)
		{
			delete socket;
		}
	}
	m_socketList.RemoveAll();
}



3 Add in CServerDemoApp

public :
	CServerSocket m_serverSock;

4 Add the startup service monitoring code in CServerDemoDlg::OnBnClickedButton1()

void CServerDemoDlg::OnBnClickedButton1()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData();
	CString strIP;
	BYTE nf1, nf2, nf3, nf4;
	m_ip.GetAddress(nf1, nf2, nf3, nf4);
	strIP.Format(_T("%d.%d.%d.%d"), nf1, nf2,nf3, nf4);
	if (m_nServerPort>1024 && !strIP.IsEmpty())
	{
		theApp.m_serverSock.Create(m_nServerPort, SOCK_STREAM, strIP);
		bool ret = theApp.m_serverSock.Listen();
		if (ret)
		{
			AfxMessageBox(_T("启动成功"));
		}
		
	}
	else
	{
		AfxMessageBox(_T("信息设置错误"));
	}

}

5 Run, start the server

Guess you like

Origin blog.csdn.net/dxm809/article/details/114335892