This article supporting source code
We know that the TCP/IP protocol is one of the most successful protocols to date and the foundation of the Internet as a whole. It has two different protocols on the Transport layer: TCP and UDP, which are very versatile, and I'll do a sample program for UDP below. The entire example has two program composition, one sends the data, the other program receives the data, completes the drawing work.
The working effect of this program is shown below:
First, send the procedure
First set up the data Dispatcher (Fason). Four data is sent: The X coordinate of the center, the y coordinate of the center, the circle radius r, and the color of the circle. Its implementation is mainly as follows:
void CFasonDlg::OnSend()
{
UpdateData(TRUE);
CString m_Getstring;
this->m_Cob.GetLBText(m_Cob.GetCurSel(),m_Getstring);
if(m_Getstring==_T("Red"))
yuan1.color=1;
if(m_Getstring==_T("Green"))
yuan1.color=2;
if(m_Getstring==_T("Blue"))
yuan1.color=3;
yuan1.x=m_x;
yuan1.y=m_y;
yuan1.r=m_r;
p=&yuan1;
CDSocket m_hSocket;
m_hSocket.Create(2330,SOCK_DGRAM);
m_hSocket.SendTo( p,sizeof(yuan1),3550,"127.0.0.1");//用结构体发送。
m_x=0;
m_y=0;
m_r=0;
m_hSocket.Close();
UpdateData(FALSE);
}
There is a trick to sending data, which is to send all the data in one structure without sending it one at a time. However, you cannot include CString data types in the structure body, such as the variable length.
Second, receive the procedure
Let's take a look at the program that receives the data end (Jieshou). As follows:
void CDASocket::OnReceive(int nErrorCode)
{
char buff[256];
int ret=0;
ret=Receive(buff,256);
if(ret==ERROR)
{
TRACE("ERROR!");
}
else
m_pDoc->Presscessding(buff);
class CAsyncSocket::OnReceive(nErrorCode);
}