{
//接收數據
recvRst = recvfrom(socket, recvBuf, 100, 0, (SOCKADDR*)&addrRecv, &len);
if (SOCKET_ERROR == recvRst)
{
break;
}
sprintf(tempBuf, "%s說:%s\r
", inet_ntoa(addrRecv.sin_addr), recvBuf);
// recvStr = tempBuf;//這種方式更加簡單不用使用消息
// ::SetDlgItemText(hWnd, IDC_EDIT_RECV, recvStr);
//使用自定義消息的方式來對控件填充內容
::PostMessage(hWnd, WM_RECVDATA, 0, (LPARAM)tempBuf);
}
return 0;
}
在OnInitDialog中調用InitSocket完成初始化工作。
InitSocket();//初始化套接字庫
RECVPARAM *pRecvParm = new RECVPARAM();
pRecvParm->socket = m_socket;
pRecvParm->hWnd = m_hWnd;
HANDLE hThreadRecv = CreateThread(NULL, 0, RecvProc, (LPVOID)pRecvParm, 0, NULL);
CloseHandle(hThreadRecv);
(5) ::PostMessage()完成將收到的數據發送給對話框。用自定義的消息參考下麵的代碼。注意要將EDitBox的MultiLine屬性選上。
<1>: 在ChatDlg.h中#define WM_RECVDATA WM_USER 1
<2>: afx_msg void OnRecvData(WPARAM wParam,LPARAM lParam);
<3>: 在ChatDlg.cpp中ON_MESSAGE(WM_RECVDATA,OnRecvData)
void CChatDlg::OnRecvData(WPARAM wParam,LPARAM lParam)
{
CString str=(char*)lParam;
CString strTemp;
GetDlgItemText(IDC_EDIT_RECV,strTemp);
str ="\r
";
str =strTemp;
SetDlgItemText(IDC_EDIT_RECV,str);
}
(6) 最後在DWORD WINAPI CChatDlg::RecvProc(LPVOID lpParameter)
中調用 ::PostMessage(hwnd,WM_RECVDATA,0,(LPARAM)tempBuf);
//不能用SendMessage()
4.對發送按紐的響應代碼:
void CChatDlg::OnBtnSend()
{
// TOD Add your control notification handler code here
DWORD dwIP;
((CIPAddressCtrl*)GetDlgItem(IDC_IPADDRESS1))->GetAddress(dwIP);
SOCKADDR_IN addrTo;
addrTo.sin_family=AF_INET;
addrTo.sin_port=htons(6000);
addrTo.sin_addr.S_un.S_addr=htonl(dwIP);
CString strSend;
GetDlgItemText(IDC_EDIT_SEND,strSend);
sendto(m_socket,strSend,strSend.GetLength() 1,0,