implementation of UDP programming in MFCCategory: 2013-06-06 12:16 2592 people reading reviews (0) favorite reports Udpsocket
1. Programming principle
UDP is a non-connected communication protocol that is much simpler than the TCP protocol. The communication process for both the server side and the client is summarized as follows:
Create socket (socket)--bind (BIND)--sends send (or receive recv)--close socket (closesocket)
2. Special Address:
In actual communication networks, we rarely use IP addresses such as "0.0.0.0" and "127.0.0.1". But on a single computer, especially for some test purposes, this type of address is useful.
(1) Loopback address: 127.0.0.1, this address can be used for the local computer test receive function, that is, when the local computer binds an IP address (such as 192.168.1.2), to the loopback address to send information m, the local computer can receive "feedback" back to the same information m (with the service side nature)
(2) All 0 network address: 0.0.0.0, can be used as the source address, representing the entire network, namely "any address"
3. Important Functions
(1) Create socket function socket ()
Function prototype:socket PASCAL FAR socket (int af, int type, int protocol);
Return value Description: Successfully returned socket, failed to return invalid_socket;
When creating a stream socket (TCP), such as: M_socket = socket (af_inet,sock_stream,0)
Create datagram Sockets (UDP), such as: M_socket = socket (af_inet,sock_dgram,0)
After the socket has been successfully created, you need to populate the sockaddr_in struct as a network function parameter:
struct SOCKADDR_IN
{
Shortint sin_family;//Address Protocol
unsigned short int sin_port;//port number
struct IN_ADDR SIN_ADDR;//IP Address
unsigned char sin_zero[8];//sockaddr retains the same size as the sockaddr_in two data structures while preserving the empty bytes.
}
As in VS2010, there are:
SOCKADDR_INADDRSOCK;//SOCKADDR_IN is defined as a macro for sockadd_in, which is defined in the header file
((cipaddressctrl*) GetDlgItem (IDC_IPADDRESS2))->getaddress (SourceIP);//Get the IP address on the control
Addrsock.sin_family=af_inet;
Addrsock.sin_port=htons (6000);
Addrsock.sin_addr. S_un. S_addr=htonl (SourceIP);//SOURCEIP indicates the host IP on which the program is running
(2) Bind function bind ()
Function prototypes:int PASCAL far bind (SOCKET s, const struct SOCKADDR far *name,int namelen)
return Value Description: Bind succeeded, return 0 value, otherwise return-1 ( Socket_error)
Such as:
int retval;
retval = Bind (M_socket, (sockaddr*) &addrsock, sizeof (SOCKADDR));//sockaddr is a macro definition of sockaddr
* (3) Create thread function CreateThread ()
Once the thread is created, it is immediately opened and the thread function is dispatched:
Recvparam *precvparam=newrecvparam;
precvparam->sock=m_socket;
precvparam->hwnd=m_hwnd;
HANDLE Hthread=createthread (Null,0,recvproc, (LPVOID) precvparam,0,null);//recvproc as thread function
CloseHandle (Hthread);
Thread functions
DWORD Winapicmychatdlg::recvproc (Lpvoidlpparameter)
{
Lpparmeter to create a thread is a function argument that is committed
Socketsock= ((recvparam*) lpparameter)->sock;
Hwndhwnd= ((recvparam*) lpparameter)->hwnd;
Deletelpparameter; Releasing objects
Sockaddr_in Addrfrom;
int len=sizeof (SOCKADDR);
Char recvbuf[200];
Char tempbuf[300];
int retval;
while (TRUE)//Necessity of creating threads
{
retval=recvfrom(sock,recvbuf,200,0, (sockaddr*) &addrfrom,&len);//Get Socket receive content
if (socket_error==retval)
Break
sprintf (TEMPBUF, "%s said:%s", Inet_ntoa (ADDRFROM.SIN_ADDR), recvbuf);
::P ostmessage (hwnd,wm_recvdata,0, (LPARAM) tempbuf);//commit message, Trigger message response
}
return 0;
}
Analysis:
struct Recvparam
{
SOCKET sock;
HWND hwnd;
};//define the struct in the header file
The creation of the thread is implemented by the function CreateThread, and the call succeeds in returning the handle and an ID.
HANDLE CreateThread (
Lpsecurity_attributes lpthreadattributes,//thread security properties, NULL for default value
DWORD dwstacksize,//the size of the thread stack, 0 is the system default value
Lpthread_start_routine lpstartaddress,//The starting address of a thread function can be a thread name
LPVOID Lpparameter,//pass to the parameters of the thread function, important!
DWORD dwcreationflags,//start immediately after thread creation, 0 means start now
Lpdword Lpthreadid//The ID number of the thread
);
(4) Get the Recvfrom function (receiving data via socket) for receiving information:
Function prototypes: ssize_trecvfrom (int sockfd,void *buf,int len,unsigned int flags, struct sockaddr*from,socket_t *fromlen);
Parameter meaning see: http://baike.baidu.com/view/1744189.htm
Function Description: The function receives data from the socket, the data is stored in the buffer, and can be read from the SOCKADDR to the relevant network parameters (such as the source address of the receiving data, etc.)
(5) Send function function sendto ()
Function prototypes: intpascal far sendto (
In SOCKET S,
In const char FAR *buf,
in int Len,
in int flags,
In const STRUCTSOCKADDR far *to,
in int tolen);
such as: SendTo (M_socket,strsend,strsend.getlength () +1,0, (sockaddr*) &addrto,sizeof (sockaddr));
4, Key points:
(1) The implementation of UDP is simple, the key is to understand the needs of each process function and how to use
(2) Creating threads for UDP communication is a more reasonable design
(3) The important step after socket creation is to populate the sockaddr_in, and the success of the binding is closely related to the structure.
(4) If the implementation mode based on human-computer interaction, UDP communication before the work can be divided into several modules, and these modules, note that you want to share a socket (such as the definition of a socket variable in a class). If there is a default UDP communication mode, you can put together the work before UDP communication, that is, define a initial function, all of these procedures can be put in.
MFC's implementation of UDP programming