A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service
Figure 1. Web chat program interface
I. Implementation Method
Microsoft's MFC encapsulates complex WinSock API functions into classes, making it easier to write network applications. CAsyncSocket classes encapsulate WinSock APIs one by one, providing more powerful and flexible methods for Senior Network programmers. This class is based on the assumption that programmers understand network communication and aims to use WinSock in MFC. programmers have the responsibility to handle tasks such as blocking, byte sequence, and character conversion between Unicode and MBCS. To provide more convenient interfaces for programmers to automatically process these tasks, MFC provides the CSocket class, which is inherited by the CAsyncSocket class, it provides a higher-level WinSock API interface than CAsyncSocket. The Csocket class and CsocketFile class can work with the Carchive class to manage the sent and received data, which makes the management data receiving and receiving more convenient. The CSocket object provides the blocking mode, which is crucial for Carchive synchronization operations. Blocking functions (such as Receive (), Send (), ReceiveFrom (), SendTo (), and Accept () do not return control until the operation is complete. Therefore, if you need lower-level control and high efficiency, use the CasyncSock class. You can use the Csocket class for convenience.
Some network applications (such as network phones and Multimedia Conferencing tools) have high real-time requirements and can directly use WinSock to send and receive data. To make full use of the advantages of MFC, the preferred solution should be the CAsyncSocket class or CSocket class in MFC. These two classes completely encapsulate WinSock APIs and provide more convenience. This example introduces the application programming models of these two classes, and introduces the relevant member functions and some concepts.
The CSocket class is inherited by CAsyncSocket. In fact, in MFC, CAsyncSocket encapsulates WinSock APIs one by one. Each CAsyncSocket object represents a Windows Socket object, the use of the CAsyncSocket class requires programmers to be familiar with network programming. In comparison, the CSocket class is a derived class of CAsyncSocket and inherits its encapsulated WinSock API.
A CSocket object represents an abstraction of a Windows Socket that is higher than the CAsyncSocket object. The CSocket class works with the CSocketFile class and the CArchive class to send and receive data, so it is easier to use. The CSocket object provides the blocking mode, Because blocking is crucial for CArchive synchronization operations. It is necessary to explain the concept of blocking: A socket can be in blocking mode or non-blocking mode. When a socket is in blocking mode (synchronous operation, its blocking function will return control until the operation is completed. Blocking is called blocking because the blocking function of this socket cannot do anything before the return of the operation is completed. If a socket is in non-blocking mode (that is, asynchronous operation), The called function will return immediately. In the CAsyncSocket class, you can use the GetLastError member function to query the final error. if the error is WSAEWOULDBLOCK, it indicates blocking, and CSocket will never return WSAEWOULDBLOCK because it manages blocking on its own. Microsoft recommends that you use the non-blocking mode whenever possible to notify the application to handle network events. However, in the CSocket class, to use CArchive to handle many problems in communication and simplify programming, some of its member functions are always congested because the CArchive class requires synchronous operations.
In the Win32 environment, if you want to use a socket with blocking nature, it should be processed in an independent working thread, and the multi-thread method should be used to prevent blocking from interfering with other threads, it will not waste CPU time on blocking. The multi-threaded method allows programmers to enjoy the convenience of simplified programming brought by CSocket, and does not affect the user interface's response to users.
CAsyncSocket Programming Model
In an MFC application, to easily process multiple network protocols without sacrificing flexibility, you can consider using the CAsyncSocket class, which is more efficient than the CSocket class. The Programming Model of CAsyncSocket class for byte flow socket is described as follows:
1. Construct a CAsyncSocket object and use the Create member function of this object to generate a Socket handle. It can be constructed in the following two methods:
|CAsyncSocket sock; // use the default parameter to generate a byte stream socket
Sock. Create ();
Or generate a datagram socket on the specified port number.
|CAsyncSocket * pSocket = newCAsyncSocket;
IntnPort = 27;
PSocket-> Create (nPort, SOCK-DGRAM );
The first method generates a CAsyncSocket object on the stack, and the second method generates a CAsyncSocket object on the stack. In the first method, the Create () member function generates a byte stream socket with the default parameter, the second method uses the Create () member function to generate a digital socket on the specified port. The prototype of the Create () function is:
|BOOL Create (UINT nSocketPort = 0, int nSocketType = SOCK_STREAM,
LPCTSTR lpszSocketAddress = NULL );
The function parameters include:
1) Port, UINT type. NOTE: If it is a service provider, a well-known port is used for the service provider to connect. If it is a customer, a typical practice is to accept the default parameter so that the socket can select an available port;
2) socket type, can be SOCK-STREAM (default value, byte STREAM) or SOCK-DGRAM (datagram );
3) socket address, such as "ftp.gliet.edu.cn" or "126.96.36.199 ".
2. If the client program is used, use the casyncsocket consumer connect () member function to connect to the service provider. If the provider program is used, use the casyncsocket consumer listen () member function to start listening. Once a connection request is received, then, call the casyncsocket ACCEPT () member function to start receiving. Note: The casyncsocket ACCEPT () member function uses a new and empty casyncsocket object as its parameter, the "null" here refers to the fact that this new object has not yet called the CREATE () member function.
3. Call other member functions of the casyncsocket class, such as receive (), receivefrom (), send (), and sendto () for data communication.
4. After the communication ends, destroy the casyncsocket object. If the casyncsocket object is generated on the stack, the object is automatically destructed when it exceeds the defined range. If it is generated on the stack, the new operator is used, the delete operator must be used to destroy the casyncsocket object.
CSocket Programming Model
The use of csocket objects involves carchive and csocketfile class objects. In the following steps, only step 1 is different for the customer and the service provider, and the other steps are the same.
1. Construct a csocket object.
2. Use the CREATE () member function of this object to generate a socket object. In the client program, unless the datagram socket is required, the CREATE () function should generally use the default parameter. The Service Provider Program must specify a port when calling CREATE. It should be noted that the carchive Class Object cannot work with the datagram (UDP) socket, so the use of the datagram socket, casyncsocket and csocket is the same.
3. If it is a client socket, call the CAsyncSocket consumer Connect () function to Connect to the service provider socket. If it is a service provider socket, call CAsyncSocket consumer Listen () start listening for connection requests from the client. After receiving the connection request, call the CAsyncSocket Accept () function to Accept the request and establish a connection. Note that the Accept () member function requires a new and empty CSocket object as its parameter, which is interpreted as the same as above.
4. Generate a CSocketFile object and associate it with the CSocket object.
5. Generate a CArchive object for receiving and sending data, and associate them with the CSocketFile object. Remember that CArchive cannot work with the datagram socket.
6. Use the Read () and Write () Functions of the CArchive object to transmit data between the customer and the service provider.
7. After the communication is completed, the CArchive, CSocketFile, and CSocket objects are destroyed.
Ii. programming steps
1. Start Visual C ++ 6.0, generate an application based on the dialog framework, and name the application "Test ";
2. Follow the Settings dialog box shown in Figure 1;
3. Use Class Wizard to add and click the message response function for the Application button;
4. Use Class Wizard to define the new Class CNewSocket in the application. The base Class is CSocket;
5. Add code and compile and run the program.
3. program code
|//////////////////////////////////////// //// // NewSocket. h: header file
# If! Defined (afx_newsocket_h1_8ce2ed73_1d56_11d3_9928_00a0c98f3e851_ded _)
# Define afx_newsocket_h1_8ce2ed73_1d56_11d3_9928_00a0c98f3e851_encoded _
# If _ MSC_VER> = 1000
# Pragma once
# Endif // _ MSC_VER >=1000
# Include <afxsock. h>
Class CNewSocket: public CSocket
//////////////////////////////////////// /// // NewSocket. cpp: implementation file
CNewSocket: CNewSocket ()
CNewSocket ::~ CNewSocket ()
# If 0
Void CNewSocket: OnAccept (int nErrorCode)
Void cnewsocket: onreceive (INT nerrorcode)
Void cnewsocket: getdlg (ctestdlg * DLG)
Void cnewsocket: onclose (INT nerrorcode)
//////////////////////////////////////// /// // Testdlg. h: header file
Class ctestdlg: Public cdialog
//////////////////////////////////////// /// // Testdlg. CPP: implementation file
Class caboutdlg: Public cdialog
CAboutDlg: CAboutDlg (): CDialog (CAboutDlg: IDD)
Void CAboutDlg: DoDataExchange (CDataExchange * pDX)
BEGIN_MESSAGE_MAP (CAboutDlg, CDialog)
CTestDlg: CTestDlg (CWnd * pParent/* = NULL */)
Void CTestDlg: DoDataExchange (CDataExchange * pDX)
BEGIN_MESSAGE_MAP (CTestDlg, CDialog)
BOOL CTestDlg: OnInitDialog ()
Void ctestdlg: onsyscommand (uint NID, lparam)
// If you add a minimize button to your dialog, you will need the code below
// The system callthis to obtain the cursor to display while the user drags
Void CTestDlg: OnConnect ()
Void CTestDlg: OnSend ()
Void CTestDlg: OnAccept ()
Void ctestdlg: onreceive ()
Void ctestdlg: ondisconnect ()
Void ctestdlg: onclose ()
Void CTestDlg: SocketReset ()
Void CTestDlg: OnServerradio ()
Void CTestDlg: OnClientradio ()
Void CTestDlg: OnSendclear ()
Void CTestDlg: OnReceiveclear ()
This example introduces the CAsyncSocket and CSocket classes, and uses the CSocket class to implement network chat programs. Readers can also use the MFC CArchive object to send and receive information, making network transmission simple and easy to use, just like using the MFC file Serialization protocol.
Start building with 50+ products and up to 12 months usage for Elastic Compute Service