⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatsocket.cpp

📁 面向软件工程的Visual C++网络程序开发
💻 CPP
字号:
// ChatSocket.cpp : implementation file

#include "stdafx.h"
#include "Client.h"
#include "ChatSocket.h"

#include "ClientDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CChatSocket

CChatSocket::CChatSocket(CClientDlg* pWnd)
{
	m_pMainWnd = pWnd;
}

CChatSocket::~CChatSocket()
{
}


// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(CChatSocket, CAsyncSocket)
	//{{AFX_MSG_MAP(CChatSocket)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif	// 0

/////////////////////////////////////////////////////////////////////////////
// CChatSocket member functions
void CChatSocket::OnReceive(int nErrorCode)
{
	if (nErrorCode != 0) {
		return;
	}

	// AsyncSelect(0);
	SOCKADDR_IN addr;
	int			len = sizeof(addr);
	char* pBuf = new char[0x1000];

	if (ReceiveFrom((void*)pBuf, 
					0x1000, 
					(SOCKADDR*)&addr, 
					&len, 
					0) < sizeof(WORD)) {
		TRACE0("faile to receive message\n.");
		return;
	}

	WORD type = *(WORD*)pBuf;
	if (type != PACKAGE_MESSAGE) {
		return;
	}

	// 将端口号改为和服务器连接的端口号
	addr.sin_port = htons((ntohs(addr.sin_port) - 1) >> 1); 

	USER_INFO* pInfo = m_pMainWnd->FindUserInfo(addr);
	if (pInfo == NULL) {
		return;
	}
	
	// 加入新消息
	CString strMsg;
	strMsg.Format(IDS_MESSAGE, 
				  pInfo->name, 
				  inet_ntoa(*(in_addr*)&addr.sin_addr.s_addr), 
				  ntohs(addr.sin_port), 
				  (char*)(pBuf + sizeof(WORD)));
	m_pMainWnd->AddMessage(strMsg);

	delete [] pBuf;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -