A network communication program based on UDP

Source: Internet
Author: User

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);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.