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

📄 mysocket.cpp

📁 该源代码实现了局域网内的信息传递、文件传输
💻 CPP
字号:
// MySocket.cpp : implementation file
//

#include "stdafx.h"
#include "BQQ.h"
#include "MySocket.h"
#include "bqqdlg.h"

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

extern hsMsg;

/////////////////////////////////////////////////////////////////////////////
// CMySocket

CMySocket::CMySocket()
{
}

CMySocket::~CMySocket()
{
	for(POSITION pos = m_connects.GetHeadPosition();pos!= NULL;)
	{
		delete (CMySocket*)m_connects.GetNext(pos);
	}
}


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

/////////////////////////////////////////////////////////////////////////////
// CMySocket member functions

void CMySocket::OnSend(int nErrorCode) 
{
	// TODO: Add your specialized code here and/or call the base class
	
	CSocket::OnSend(nErrorCode);
}

void CMySocket::OnReceive(int nErrorCode) 
{
	// TODO: Add your specialized code here and/or call the base class
	//rvMsg();
	ReceiveTheMsg();
	CSocket::OnReceive(nErrorCode);
}

void CMySocket::OnClose(int nErrorCode) 
{
	// TODO: Add your specialized code here and/or call the base class
	((CBQQApp*)AfxGetApp())->closed =TRUE;
	CSocket::OnClose(nErrorCode);
}

void CMySocket::OnAccept(int nErrorCode) 
{
	// TODO: Add your specialized code here and/or call the base class
	CSocket::OnAccept(nErrorCode);
	CMySocket *pSock = new CMySocket();
	if(this->Accept(*pSock))
	{
		m_connects.AddTail(pSock);
	}
	else
		delete pSock;
}



BOOL CMySocket::updateWnd(CString from,CString msg)
{
	ASSERT(AfxGetMainWnd()!=NULL);
	ASSERT(AfxGetMainWnd()->GetDlgItem(IDC_INOUT)!=NULL);
	ASSERT(AfxGetMainWnd()->GetDlgItem(IDC_ADDRLIST)!=NULL);
	if(!(((CEdit*)AfxGetMainWnd()->GetDlgItem(IDC_INOUT))->GetStyle()&ES_READONLY ))
		((CEdit*)AfxGetMainWnd()->GetDlgItem(IDC_INOUT))->GetWindowText(((CBQQApp*)AfxGetApp())->tmpMsg);
	int len = AfxGetMainWnd()->GetDlgItem(IDC_INOUT)->GetWindowTextLength();
	((CEdit*)AfxGetMainWnd()->GetDlgItem(IDC_INOUT))->SetReadOnly(FALSE);
	((CEdit*)AfxGetMainWnd()->GetDlgItem(IDC_INOUT))->SetSel(len,len);
	((CEdit*)AfxGetMainWnd()->GetDlgItem(IDC_INOUT))->ReplaceSel(msg);
	((CEdit*)AfxGetMainWnd()->GetDlgItem(IDC_INOUT))->SetReadOnly(TRUE);
	CString add="";
	AfxGetMainWnd()->GetDlgItem(IDC_ADDRLIST)->GetWindowText(add);
	if(add.IsEmpty())
		AfxGetMainWnd()->GetDlgItem(IDC_ADDRLIST)->SetWindowText(from);
	((CDimEditCtrl*)AfxGetMainWnd()->GetDlgItem(IDC_ADDRLIST))->SetShowDimControl( false );
	AfxGetMainWnd()->GetDlgItem(IDC_INPUTMSG)->EnableWindow(TRUE);

	::PostMessage(AfxGetMainWnd()->m_hWnd,WM_LIBEN,IDR_MAINFRAME,WM_LBUTTONDOWN);
	return TRUE;
}

BOOL CMySocket::ReceiveTheMsg()
{
	int nRead=0;
	DWORD dwBytesToWrite = 0;
	byte *buffer= new byte[50];
	memset(buffer, 0, 50);
	nRead = Receive(buffer, 50); 
	switch (nRead)
   {
	   case 0:
		  Close();
		  break;
	   case SOCKET_ERROR:
		  if (GetLastError() != WSAEWOULDBLOCK) 
		  {
			 AfxMessageBox ("Error occurred");
			 Close();
		  }
		  break;
	   default:
	  		CHAR flag[MAX_NAME_SIZE];
			CHAR from[MAX_NAME_SIZE];
			CHAR content[MAX_BUFFER_SIZE+1];
			memset(content, 0 , MAX_BUFFER_SIZE+1);
			strcpy(flag,(LPCSTR)buffer);
			int pos = strlen(flag) + 1;
			strcpy(from, (LPCSTR)buffer+pos);
			CString szTemp(flag),idd(from);
			CString name ="",sender="",len="0",Ipp="0";
			int dataLength=0;
			int lf=-1,ls=-1,ts=-1;
			lf= idd.FindOneOf("$");
			sender = idd.Left(lf);
			ls= idd.Find("$",lf+1);
			name = idd.Mid(lf+1,ls-lf-1);
			ts = name.FindOneOf("/");
			if(ts>0)
			{
				Ipp = name.Mid(ts+1);
				name = name.Left(ts);
			}
			len = idd.Mid(ls+1);
			int length=0;
			length = StrToInt(len);
			if (szTemp.CompareNoCase("A") == 0 )
			{
				CString promt="",workDir=".";
				CString newFile="";
				int read=0,pos=0;
				byte *fileContent = new byte[length+1];
				memset(fileContent,0,length+1);
				do{					
					read = Receive(fileContent+pos,length);
					pos+=read;
					length-=read;
				}while(length>0);
				/*/TCHAR szDir[100];
				//::GetCurrentDirectory(100,szDir);
				//workDir = CString(szDir);
				TCHAR exeFullPath[MAX_PATH];
				GetModuleFileName(NULL,exeFullPath,MAX_PATH);
				workDir = CString(exeFullPath);
				int curPost=0,posx=0;
				while((curPost=workDir.Find('\\',curPost+1))!=-1)
				{
					posx = curPost;
				}
				/////////////////
				//workDir = workDir.Left(posx+1);
				//newFile.Format("%s\\BQQ_%s",workDir,name);
				/*////////////////
				CFileDialog flDlg(FALSE, NULL, name,
					OFN_CREATEPROMPT | OFN_EXPLORER | OFN_HIDEREADONLY,
					"All files|*.*||", AfxGetMainWnd());
				if(flDlg.DoModal()==IDOK)
				{
					newFile = flDlg.GetPathName();
					CFile destFile(newFile, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
					destFile.Write(fileContent, pos); // Write it
					destFile.Close();
					promt.Format("\r\n%s发给您的%s文件已保存到%s!\r\n",sender,name,newFile);
					((CBQQApp*)AfxGetApp())->hisMsg+= promt;
					MessageBox(NULL,promt,"提示",MB_ICONINFORMATION|MB_OK);
				}
				delete fileContent;
			}
			else
			{
				CString tim="",revMsg="",senderMask="";
				int read=0,ps=0;
				byte *txtContent = new byte[length+1];
				memset(txtContent,0,length+1);
				do{
					read = Receive(txtContent+ps,length);
					ps+=read;
					length-=read;
				}while(length>0);
				CString txt((const unsigned char*)txtContent);					
				CTime t = CTime::GetCurrentTime();
				tim = t.Format( "%m月%d日%H:%M:%S");
				 if(szTemp.CompareNoCase("B") == 0) //anonumous
				 {
					revMsg.Format("\r\n消息来自***[%s]:\r\n%s\r\n",tim,txt);
					senderMask="***";
				 }
				 else
				 {
				
					if(szTemp.CompareNoCase("C") == 0)
					{
						CString prom ="",suc="";
						prom.Format("文件发送失败!");
						suc.Format("文件发送成功!");
						if(!SendTheFile(sender,name,Ipp))
							MessageBox(NULL,prom,"提示",MB_ICONERROR|MB_OK);
						else
							MessageBox(NULL,suc,"提示",MB_ICONINFORMATION|MB_OK);
						delete buffer;
						delete txtContent;
						return TRUE;
					}
					else if(szTemp.CompareNoCase("D") == 0)
					{
						ResponseForFile(sender,name,Ipp);
					}
					else if(szTemp.CompareNoCase("N") == 0)
					{
						MessageBox(NULL,"对方拒绝接收文件!","提示",MB_ICONINFORMATION|MB_OK);
					}
					revMsg.Format("\r\n消息来自%s[%s]:\r\n%s\r\n",sender,tim,txt);
					senderMask =sender;
				 }
				 ((CBQQApp*)AfxGetApp())->hisMsg+=revMsg;
				 updateWnd(senderMask,revMsg);
				 delete txtContent;
			}
	MessageBeep(-1);
   }		
	delete buffer;
	return TRUE;

}

BOOL CMySocket::SendTheFile(CString sender,CString name,CString Ipp)
{
	//send the A flag and the file;
	if(Ipp=="0")
		return FALSE;
	byte *buf = new byte[50];
	CMySocket rtnSock;
	SOCKADDR_IN add_in;
	add_in.sin_family = AF_INET;
	ZeroMemory(add_in.sin_zero,0) ;
	add_in.sin_addr.s_addr = StrToLong(Ipp);
	add_in.sin_port = htons(2118);
	rtnSock.Close();
	rtnSock.Create();
	rtnSock.Connect((SOCKADDR*)&add_in, sizeof(add_in));
	/////////
	CFile myFile;
	CString flg = "",info="",file="",fileName="",hostName="";
	int rtn=0;
	hostName =((CBQQApp*)AfxGetApp())->senderName;
	fileName = ((CBQQApp*)AfxGetApp())->sendFileName;
	file = ((CBQQApp*)AfxGetApp())->sendFileFullName;
	if(fileName.IsEmpty() || hostName.IsEmpty())
	{
		rtnSock.Close();
		return FALSE;
	}
	memset(buf, 0, 50);
	if(!myFile.Open(file, CFile::modeRead | CFile::typeBinary))
	{
		rtnSock.Close();
		return FALSE;
	}
	int myFileLength = myFile.GetLength(); 
	flg = "A";
	int len = flg.GetLength();
	memcpy(buf, flg,1);
	if(fileName.GetLength()>(30-hostName.GetLength()))
		fileName= fileName.Right(47-hostName.GetLength()-sizeof(myFileLength));
	info.Format("%s$%s$%d",hostName,fileName,myFileLength);
	int sz = info.GetLength();
	memcpy(buf+2, info,sz);
	byte *data = new byte[myFileLength+1]; 
	ZeroMemory(data,myFileLength+1);
	myFile.Read(data, myFileLength);
	byte *sdData =  new byte[myFileLength+51];
	ZeroMemory(sdData,myFileLength+51);
	memcpy(sdData,buf,50);
	memcpy(sdData+50,data,myFileLength);
	rtn = rtnSock.Send(sdData,myFileLength+50);
	//((CButton*)AfxGetMainWnd()->GetDlgItem(IDC_INCLUDEATTACH))->SetCheck(BST_UNCHECKED);
	((CButton*)AfxGetMainWnd()->GetDlgItem(IDC_INCLUDEATTACH))->EnableWindow(FALSE);
	((CButton*)AfxGetMainWnd()->GetDlgItem(IDC_INCLUDEATTACH))->SetWindowText("没有附件");
	AfxGetMainWnd()->GetDlgItem(IDC_ATTACH)->SetWindowText("附件(&F)");
	//((CBQQApp*)AfxGetApp())->sendFileFullName = "";
	//((CBQQApp*)AfxGetApp())->sendFileName ="";
	((CBQQApp*)AfxGetApp())->hasAttachment = FALSE;
	delete data;
	delete sdData;
	delete buf;
	rtnSock.Close();
	/////////
	if(rtn<=0)
		return FALSE;
	return TRUE;
}

BOOL CMySocket::ResponseForFile(CString sender,CString name,CString Ipp)
{
	CString promt="",flg = "",info="",file="",fileName="",hostName="",ms="YES",hostIP="";
	promt.Format("%s发给您一个%s文件,接收吗?",sender,name);
	if(MessageBox(NULL,promt,"提示",MB_ICONINFORMATION|MB_OKCANCEL)==IDOK)
	{
		flg = "C";
	}
	else
	{
		flg = "N";
		ms = "暂不能接收您的文件!";
	}
	byte *buf = new byte[50];
	CMySocket rtnSock;
	SOCKADDR_IN add_in;
	add_in.sin_family = AF_INET;
	ZeroMemory(add_in.sin_zero,0) ;
	add_in.sin_addr.s_addr = StrToLong(Ipp);
	add_in.sin_port = htons(2118);
	rtnSock.Close();
	rtnSock.Create();
	rtnSock.Connect((SOCKADDR*)&add_in, sizeof(add_in));
	/////////
	CFile myFile;
	int rtn=0,msLen = ms.GetLength();
	memset(buf, 0, 50);
	int len = flg.GetLength();
	memcpy(buf, flg,1);
	hostName =((CBQQApp*)AfxGetApp())->senderName;
	hostIP = ((CBQQApp*)AfxGetApp())->hostIP;
	info.Format("%s$***/%s$%d",hostName,hostIP,msLen);
	int sz = info.GetLength();
	memcpy(buf+2, info,sz);
	byte *sdData =  new byte[msLen+51];
	ZeroMemory(sdData,msLen+51);
	memcpy(sdData,buf,50);
	memcpy(sdData+50,ms,msLen);
	rtn = rtnSock.Send(sdData,msLen+50);
	delete sdData;
	delete buf;
	rtnSock.Close();

	if(rtn<=0)
		return FALSE;

	return TRUE;
}

⌨️ 快捷键说明

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