一、概述
"使用者資料包通訊協定"(User Datagram Protocol,簡稱UDP)是基於不需連線的通訊協定,不保證可靠資料的傳輸;"傳輸控制通訊協定"(Transmission Cotrol Protocol,簡稱TCP)是基於串連的通訊協定,可提供個兩台電腦之間可靠無差錯的資料轉送。但是UDP能夠向若干台目標電腦發送資料;接收發自若干個源電腦的資料。而在多台電腦構成的模擬或控制系統中,經常會出現多台電腦進行資料轉送,所以在模擬或控制軟體中採用UDP協議的較多。
二、代碼說明
為了便於說明模擬或控制中對多個變數的傳輸,採用結構體的資料結構形式。建立兩個工程分別為發送Send工程和接收工程。其中發送資料的工程代碼為:
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協議傳輸的結構體資料。