分类: C/C++
2008-03-13 17:43:00
void CSendDlg::OnButtonSend() //发送数据
{
//发送数据、对象定义
struct _PLATFORM
{
int err_num;//故障代码
//控制(仿真)参数
int sj;
int hy;
int zy;
} Platform,*pPlatform;
CSocket m_SendSocket;//构造一个套接字对象
//发送数据的初始化
Platform.err_num=0;//系统正常
Platform.sj=200;
Platform.hy=300;
Platform.zy=100;
pPlatform=&Platform;
//数据发送
m_SendSocket.Create(2330,SOCK_DGRAM);//创建一个套接字句柄(UDP)
m_SendSocket.SendTo( pPlatform,sizeof(Platform),3550,"127.0.0.1");//发送数据给本地计算机
}
接收数据的工程代码为: void CReceiveDlg::OnButtonReceive()
{
//数据、对象定义
struct _PLATFORM1//为了区别于发送数据的数据结构
{
int err_num1;//故障代码
//控制(仿真)参数
int sj1;
int hy1;
int zy1;
} Platform1,*pPlatform1;
CSocket m_ReceiveSocket;
char *buff1[256];
CString str1;
CString str2;
CString str3;
CString str4;
//接收数据
m_ReceiveSocket.Create(3550,SOCK_DGRAM);
m_ReceiveSocket.Receive(buff1,256);
//接收数据的测试
pPlatform1=(struct _PLATFORM1*)buff1;//非常关键
str1.Format("%d",Platform1.err_num1=pPlatform1->err_num1);
str2.Format("%d",Platform1.sj1=pPlatform1->sj1);
str3.Format("%d",Platform1.hy1=pPlatform1->hy1);
str4.Format("%d",Platform1.zy1=pPlatform1->zy1);
AfxMessageBox(str1);
AfxMessageBox(str2);
AfxMessageBox(str3);
AfxMessageBox(str4);
}
程序执行时,要先触发"接受数据"按钮再触发"发送数据"按钮可以得到通过UDP协议传输的结构体数据。 
