CAsyncSocket进行UDP通信

客户端代码:

CString    m_ServerIP;
CString m_ClientIP;
int m_ClientPort;
CString m_ReceiveData;
UINT m_ServerPort;
CAsyncSocket m_sockReceive;

m_ServerIP="127.0.0.1";
m_ClientIP="127.0.0.1";
m_ClientPort=6665;
m_ServerPort=6666;

void CSocketUDPClientDlg::OnReceive()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
if (m_sockReceive.Create(m_ClientPort,SOCK_DGRAM,NULL))
{
m_sockReceive.Bind(m_ClientPort,m_ClientIP);
SetTimer(1,2000,NULL);
GetDlgItem(IDC_RECEIVE)->EnableWindow(FALSE);
GetDlgItem(IDC_STOP)->EnableWindow(TRUE);
}
else
{
AfxMessageBox("创建套接字失败");
}
}

void CSocketUDPClientDlg::OnStop()
{
// TODO: Add your control notification handler code here
KillTimer(1);
m_sockReceive.Close();
m_ReceiveData="停止接收数据";
UpdateData(FALSE);
GetDlgItem(IDC_RECEIVE)->EnableWindow(TRUE);
GetDlgItem(IDC_STOP)->EnableWindow(FALSE);
}

void CSocketUDPClientDlg::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
char szRec[20];
int iRec=m_sockReceive.ReceiveFrom(szRec,10,m_ServerIP,m_ServerPort,0);
if (iRec==-1)
{
m_ReceiveData="停止接收数据";
}
else
{
szRec[iRec]=NULL;
m_ReceiveData=szRec;
}
UpdateData(FALSE);
CDialog::OnTimer(nIDEvent);
}

服务端代码:

 1 CString    m_ServerIP;
2 CString m_ClientIP;
3 int m_ServerPort;
4 int m_ClientPort;
5 CAsyncSocket m_socketSend;
6
7 m_ServerIP="127.0.0.1";
8 m_ClientIP="127.0.0.1";
9 m_ClientPort=6665;
10 m_ServerPort=6666;
11
12 oid CSocketUDPServerDlg::OnSend()
13 {
14 // TODO: Add your control notification handler code here
15 UpdateData(TRUE);
16 if (m_socketSend.Create(m_ServerPort,SOCK_DGRAM,NULL))
17 {
18 m_socketSend.Bind(m_ServerPort,m_ServerIP);
19 SetTimer(1,2000,NULL);
20 GetDlgItem(IDC_SEND)->EnableWindow(FALSE);
21 GetDlgItem(IDC_STOP)->EnableWindow(TRUE);
22 }
23 else
24 AfxMessageBox("套接字创建失败");
25 }
26
27 void CSocketUDPServerDlg::OnStop()
28 {
29 // TODO: Add your control notification handler code here
30 KillTimer(1);
31 m_socketSend.Close();
32 GetDlgItem(IDC_SEND)->EnableWindow(TRUE);
33 GetDlgItem(IDC_STOP)->EnableWindow(FALSE);
34 }
35
36 void CSocketUDPServerDlg::OnTimer(UINT nIDEvent)
37 {
38 // TODO: Add your message handler code here and/or call default
39 static iIndex=0;
40 char szSend[20];
41 sprintf(szSend,"101%d",iIndex++);
42 int iSend=m_socketSend.SendTo(szSend,10,m_ClientPort,m_ClientIP,0);
43 TRACE("发送了%d个字节",iSend);
44 CDialog::OnTimer(nIDEvent);
45 }




 

posted on 2011-12-22 16:47  Sunny_NUAA  阅读(1986)  评论(0编辑  收藏  举报

导航