带界面的UDP聊天程序

BEGIN_MESSAGE_MAP(CMFCApplication38Dlg, CDialogEx)
	ON_MESSAGE(WM_USER+1,OnRecvData)
	ON_BN_CLICKED(IDC_BTN_SEND, &CMFCApplication38Dlg::OnBnClickedBtnSend)
END_MESSAGE_MAP()


// CMFCApplication38Dlg 消息处理程序

BOOL CMFCApplication38Dlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	if(!AfxSocketInit())
	{
		AfxMessageBox(_T("加载套接字失败!"));
		return FALSE;
	}
	if(!InitSocket())
	{
		return FALSE;
	}
	// TODO: 在此添加额外的初始化代码
	RECVPARAM *param = new RECVPARAM;
	param->hwnd = m_hWnd;
	param->socket = m_socket;
	handle = CreateThread(NULL,0,RecvThread,(LPVOID)param,0,NULL);
	CloseHandle(handle);
	return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE
}

BOOL CMFCApplication38Dlg::InitSocket()
{
	m_socket = socket(AF_INET,SOCK_DGRAM,0);
	if(INVALID_SOCKET == m_socket)
	{
		AfxMessageBox(_T("套接字创建失败!"));
		return FALSE;
	}
	SOCKADDR_IN socketaddr;
	socketaddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
	socketaddr.sin_family = AF_INET;
	socketaddr.sin_port = htons(6000);

	int retvel;

	retvel = bind(m_socket,(SOCKADDR*)&socketaddr,sizeof(SOCKADDR));

	if(SOCKET_ERROR == retvel)
	{
		closesocket(m_socket);
		AfxMessageBox(_T("绑定失败!"));
		return FALSE;
	}
	return TRUE;
}

DWORD WINAPI CMFCApplication38Dlg::RecvThread(LPVOID lpParam)
{
	SOCKET socket = ((RECVPARAM*)lpParam)->socket;
	HWND hwnd = ((RECVPARAM*)lpParam)->hwnd;
	delete lpParam;
	SOCKADDR_IN socketaddr;
	int len = sizeof(SOCKADDR);
	char RecvBuf[200];
	char tempBuf[200];
	int retval;
	while(TRUE)
	{
		retval = recvfrom(socket,RecvBuf,200,0,(SOCKADDR*)&socketaddr,&len);

		sprintf_s(tempBuf,"%s:%s",inet_ntoa(socketaddr.sin_addr),RecvBuf);
		::PostMessage(hwnd,WM_USER+1,0,(LPARAM)tempBuf);
	}
	return 0;
}

LRESULT CMFCApplication38Dlg::OnRecvData(WPARAM wparam,LPARAM lparam)
{
	CString str((char *)lparam);
	CString strTemp;
	GetDlgItemText(IDC_EDIT_RECV,strTemp);
	//strTemp +="\r\n";
	str = strTemp + str;
	str += "\r\n";
	SetDlgItemText(IDC_EDIT_RECV,str);
	return 0;
}

void CMFCApplication38Dlg::OnBnClickedBtnSend()
{
	// TODO: 在此添加控件通知处理程序代码
	DWORD dwIP;
	((CIPAddressCtrl*)GetDlgItem(IDC_IPADDRESS1))->GetAddress(dwIP);
	SOCKADDR_IN addrTo;
	addrTo.sin_addr.S_un.S_addr = htonl(dwIP);
	addrTo.sin_family = AF_INET;
	addrTo.sin_port = htons(6000);
	CString strSend;
	GetDlgItemText(IDC_EDIT_SEND,strSend);
	
	char SendBuf[200];
	int i;
	for(i=0;i
带界面的UDP聊天程序_第1张图片

你可能感兴趣的:(网络编程,MFC)