Use MFC to quickly implement network programming casyncsocket

Source: Internet
Author: User
Tags socket error
Use MFC to quickly implement network programming casyncsocket
This article address: http://tech.163.com/05/1110/16/2277UC610009159F.html [click here copy address]

With the development of computer network, computer network programming becomes increasingly important in the process of programming. Due to the superiority of the C ++ language in underlying operations, many articles have introduced the socket programming method using VC ++. However, it is cumbersome to directly use the dynamic Connection Library wsock32.dll for operations. In fact, the VC ++ MFC class library provides a socket class such as casyncsocket. It is very convenient to use it to implement socket programming.

---- This article will use an echo routine to introduce the usage of the casyncsocket class.

----I. Client

---- 1. Create a dialog based project: csockclient.

---- 2. Design dialog box

---- Remove the OK and cancle buttons, add the id_connect, id_send, and id_exit buttons, and add the ListBox controls idc_listmsg and edit controls idc_editmsg, and add variables for the ccsockclientdlg class in classwizard in the following table.Control
ID 
Type Member 
IDC_EDITMSG 
CEdit m_MSGIDC_LISTMSG 
ClistBox 
m_MSGS

---- 3. the casyncsocket class uses the docallback function to process the MFC message. When a network event occurs, the docallback function is based on the network event type: fd_read, fd_write, fd_accept, and fd_connect call the onreceive, onsend, onaccept, and onconnect functions respectively. Because MFC defines these event handler functions as virtual functions, it is necessary to generate a new C ++ class to overload these functions. The procedure is as follows:

---- Inherit the casyncsocket class in the public mode and generate the new class mysock;

---- Add the virtual functions onreceive, onconnect, and onsend to the mysock class

---- 4. Add the following code to mysock. CCP:#include "CSockClient.h"#include
"CSockClientDlg.h"

---- 5. Add the following code in mysock. h:Public: bool m_bconnected;
// Whether to connect uint m_nlength;
// Message length: Char m_szbuffer [4096];
// Message Buffer

---- 6. Reload each function in mysock. CCPMysock: mysock () {m_nlength = 0;
Memset (m_szbuffer, 0, sizeof (m_szbuffer ));
M_bconnected = false;} mysock ::~ Mysock (){
// Close the socket If (m_hsocket! = Invalid_socket)
Close ();}
Void mysock: onreceive (INT nerrorcode ){
M_nlength = receive (m_szbuffer, sizeof (m_szbuffer), 0 );
// The following two lines of code are used to obtain the ccsockclientapp * PAPP = (ccsockclientapp *) afxgetapp ();
Ccsockclientdlg * pdlg = (ccsockclientdlg *) PAPP-> m_pmainwnd;
Pdlg-> m_msgs.insertstring (0, m_szbuffer); memset (m_szbuffer, 0, sizeof (m_szbuffer ));
Casyncsocket: onreceive (nerrorcode);} void mysock: onsend (INT nerrorcode ){
Send (m_szbuffer, m_nlength, 0); m_nlength = 0;
Memset (m_szbuffer, 0, sizeof (m_szbuffer ));
// Continue to submit a "read" network event to receive the Server Message asyncselect (fd_read );
Casyncsocket: onsend (nerrorcode);} void mysock: onconnect (INT nerrorcode ){
If (nerrorcode = 0 ){
M_bconnected = true;
Ccsockclientapp * PAPP = (ccsockclientapp *) afxgetapp ();
Ccsockclientdlg * pdlg = (ccsockclientdlg *) PAPP-> m_pmainwnd;
Memcpy (m_szbuffer, "connected to", 13 );
Strncat (m_szbuffer, pdlg-> m_szserveradr,
Sizeof (pdlg-> m_szserveradr ));
Pdlg-> m_msgs.insertstring (0, m_szbuffer );
Asyncselect (fd_read );
//// Submit a "read" network event to be received}
Casyncsocket: onconnect (nerrorcode );}

---- 7. The new dialog box idd_addr is used to enter the IP address and port, and generate a new class caddrdlg. Add two edit controls: idc_addr and idc_port. In the following table, add variables for the caddrdlg class in classwizard.Control
ID Type MemberIDC_Addr CString m_AddrIDC_Port Int m_Port

---- 8. Add code in csockclientdlg. CCP#include "AddrDlg.h"protected:
int TryCount; 
MySock m_clientSocket; 
UINT m_szPort;public: char m_szServerAdr[256];

---- 9. Double-click the "Connect" button in the idd_csockclient_dialog dialog box to add the following code:Void ccsockclientdlg: onconnect ()
{
M_clientsocket.shutdown (2 );
M_clientsocket.m_hsocket = invalid_socket;
M_clientsocket.m_bconnected = false;
Caddrdlg m_dlg; // default port 1088m_dlg.m_port = 1088;
If (m_dlg.domodal () = idok &&! M_dlg.m_addr.isempty ()){
Memcpy (m_szserveradr, m_dlg.m_addr, sizeof (m_szserveradr ));
M_szport = m_dlg.m_port; // create a timer and connect every 1 second until it is connected or trycount> 10 settimer (, null );
Trycount = 0 ;}}

---- 10. Add the Windows message wm_timer response function ontimervoid CCSockClientDlg::OnTimer(UINT
nIDEvent) { 
if (m_clientSocket.m_hSocket==INVALID_SOCKET) { 
BOOL bFlag=m_clientSocket.Create(0,SOCK_STREAM,FD_CONNECT); 
if(!bFlag) { AfxMessageBox("Socket Error!"); 
m_clientSocket.Close(); 
PostQuitMessage(0); 
return; 
} } 
m_clientSocket.Connect(m_szServerAdr,m_szPort); 
TryCount++; 
if (TryCount >=10 || m_clientSocket.m_bConnected) { 
KillTimer(1); 
if (TryCount >=10) AfxMessageBox("Connect Failed!"); 
return; } 
CDialog::OnTimer(nIDEvent);}

---- 11. Double-click the "send" button in the idd_csockclient_dialog dialog box to add the following code:void CCSockClientDlg::OnSend()

if (m_clientSocket.m_bConnected) 
{m_clientSocket.m_nLength=m_MSG.GetWindowText(m_clientSocket.m_szBuffer, sizeof(m_clientSocket.m_szBuffer)); 
m_clientSocket.AsyncSelect(FD_WRITE); 
m_MSG.SetWindowText(""); }}

---- 12. Double-click the "close" button in the idd_csockclient_dialog dialog box to add the following code:Void ccsockclientdlg: onexit ()
{
// Close socketm_clientsocket.shutdown (2); // close the dialog box enddialog (0 );}

---- 12. When you run this project, you can enter the host name or IP address during connection. The casyncsocket class will automatically handle this problem.

----Ii. Server

---- Server programming is similar to client programming. The following describes the listen and accept functions.

---- 1. Create a cnewsocket class and reload the onreceive and onsend functions of the casyncsocket class,

For details about how to display and send information, refer to the client program. In this example, the received information is kept intact.

To implement the echo function. The Code is as follows:Cnewsocket: onreceive (INT nerrorcode ){
M_nlength = receive (m_szbuffer, sizeof (m_szbuffer), 0 );
// Directly forward the message asyncselect (fd_write);} cnewsocket: onsend (INT nerrorcode) {send (m_szbuffer, m_nlength, 0 );}

---- 2. Create a cmyserversocket class. The onaccept function code for reloading the casyncsocket class is as follows:

---- Declare variables in myserversocket. hPublic: cnewsocket * m_psocket;
Void cmyserversocket: onaccept (INT nerrorcode ){
// Listen to the connection request and call the accept Function
Cnewsocket * psocket = new cnewsocket ();
If (accept (* psocket )){
Psocket-> asyncselect (fd_read );
M_psocket = psocket;
} Else
Delete psocket ;}

---- 3. Add a "listener" button for the dialog box and add the following code:

---- Declare the variable in csockserverdlg. CCPPublic: cmyserversocket m_srvrsocket;
Void ccsockserverdlg: onlisten () {if
(M_srvrsocket.m_hsocket = invalid_socket ){
Bool bflag = m_srvrsocket.create
(Userport, sock_stream, fd_accept );
If (! Bflag) {afxmessagebox ("socket Error !");
M_srvrsocket.close ();
Postquitmessage (0 );
Return ;}}
// The Listener succeeds. Wait for the connection request if (! M_srvrsocket. Listen (1 )){
Int nerrorcode = m_srvrsocket.getlasterror ();
If (nerror! = Wsaewouldblock)
{
Afxmessagebox ("socket Error !");
M_srvrsocket.close ();
Postquitmessage (0 );
Return;
}}}

---- 4. Currently, the program can only implement the echo function and forward the information intact.

Cnewsocket * psocket = new cnewsocket ();

The obtained socket pointer is stored in a clist or array, and all connections are read and written as the client.

----Iii. Summary

---- Casyncsocket class provides great convenience for us to use socket. The wsastartup process and bind process of the socket are simplified to the create process,

Many complex variable types are simplified to string and integer operations, especially casyncsocket.

Class asynchronous features, can completely replace tedious thread operations. MFC provides a large number of class libraries. If we can use them flexibly, the programming efficiency will be greatly improved.

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.