Implement network asynchronous communication with the Socket interface

zhaozj2021-02-08  266

Using the Socket interface to implement network asynchronous communication Ma Aimin VC 4.1 The above-mentioned version of the above version provides a Socket interface, which can easily communicate with network communication. This article uses the Socket interface in an application to implement asynchronous communication. Since the server and client master program are waiting for information in asynchronous communication, there is a broader application area. 1. Establishing an application framework To facilitate the interrelationship between the program, assume that the AppWizard that has been used with VC has established a single document type application framework. The project is named asock, which includes the following files: asockapp.h asockapp.cpp Mainfraim.h mainfraim.cpp childview.h childview.cpp Writes a application that can perform asynchronous communication on the basis of the above program framework. 2. Flow socket communication principle stream socket is widely used due to high reliability. Its communication principle is: both the server and the client must establish a communication socket, and the server should first enter the listening state, and then the client sleeve message issues a connection request. After receiving the request, establish another socket In communication, the socket responsible for listening is still listening. If other customers send a connection request, build a socket. By default, you can receive up to 5 client connection requests, and establish communication relationships. 3. Define the network asynchronous communication of the socket in this example, two new classes are derived by asynchronous socket class CasycNSocket. The generation of code can use ClassWizard to create a program framework, give two derived classes Named MySocket and Servesocket, the base class used when generated is CasyCNSocket, and can put them in the same set of files (this example is Mysocket. H and mysocket.cpp). Then add OnCept () and onRecEive () to the MySocket class in ClassWizard; join the onReceive () function for the Servesocket class. Note that these functions are overloaded functions, and the way to naming it will not be named. The method of joining the function is to select the last row in the ClassWizard's Object IDS window, and then select the corresponding function in the Message window. The functionality of the two derived classes is: MySocket class is used to establish a socket on the server and the client, which is used to listen and communicate; the Servesocket class is used to establish a communication socket in the server, which is in the server After the connection request is established, this example is used as a member variable of the MySocket class. In order to enable the server to respond to the request of multiple customers, you can establish a socket type of the SERVESOCKET type, and a logger is set, and the number of requests has been received, which is set in the constructor of MySocket. 0. The key to complete asynchronous communication is the above three overload functions, which can be automatically called from the network, which can be automatically called to complete the reception. In this case, the onaccept () function issues a message representing its serial number after receiving the connection request; the two onRecEive () functions are prompted and the received information will be sent back after confirmation. The source code of the above two derived classes is online, the URL is www.pc.computing.com.cn. 4. Complete the server or client settings With the settings completed by the menu item, there are multiple arrangements. In this example, the settings are arranged in the cchildview class in the CChildView class for easy display.

First use the Resource Editor to add two options in the main menu, and define their ID, then use ClassWizard to add the response function of these two IDs in the CChildView class, and create a socket in which the socket is created. Search or start connectivity. In order to facilitate the observation of the working process, you can add the corresponding output statement, in addition, there must be a #include "mysocket.h" statement in frontview.h and childview.cpp files. To simplify the program, this program directly writes the IP address of the service host, and therefore, the server is specified, and the client cannot be changed, but the location of the client is not limited. 5. The use of the program This program can communicate asynchronously between different hosts in the same network. Take two hosts as an example, first start this program on the specified host, select the Server option in the menu, so that the program enters the listening state; then start this program on another host and select the client option, send a connection to the server. Request; After the server receives the connection request, the onaccept () function automatically calls the onaccept () function, issues corresponding information to it according to the client's request; after the client receives the information sent by the server, display a prompt box on the screen, press " After confirming the button, the client sends this information back to the server; after the server receives the information sent back to the client, the processing mode is the same as the client, which is true that this information is delivered in two computers. It is worth noting that this program can also do other jobs during waiting for information, such as an option on the menu, etc., of course, other work can be added. Run this program and select up to five clients as the server, so six instances of this program can be run at the same time, one of which is set to the server, and the other is set to the client. Since the server is actually communicating with the client with five sockets, the communication process of the point-to-peer point will not interfere with each other. 6. Source Procedures This article gives the changed file code (ie Mysocket and ChildView's .H and .CPP file source code) as follows, these programs are compiled under VC 6.0 and in the network of the author units The environment is running successfully.

mysocket.h file: // socket classes derived class ServeSocket: public CAsyncSocket {public: char rx_buf [100]; int ServeNo; public: ServeSocket (); virtual ~ ServeSocket (); public: // ClassWizard generated virtual function overrides // {{AFX_VIRTUAL (serveSocket) public: virtual void OnReceive (int nErrorCode); //}} AFX_VIRTUAL} class mySocket: public CAsyncSocket {public: serveSocket servesocket [5]; int AcceptNo; int ConnectNo; char rx_buf [100]; public: mySocket (); virtual ~ mySocket (); public: // ClassWizard generated virtual function overrides // {{AFX_VIRTUAL (mySocket) public: virtual void OnAccept (int nErrorCode); virtual void OnReceive (int nErrorCode); //} } AFX_VIRTUAL} ISOCKET.CPP files: void servesocket :: OnRecEive (int NerrorCode) {if (Receive (RX_BUF, 100)) {// Re-send received information messagebeep (0); AFXMESSAGEBOX; Send (rx_buf, 10);} else {// receive Error AfxMessageBox ( "receive failed", 14); return;} CAsyncSocket :: OnReceive (nErrorCode);} void MySocket :: OnAccept (int nErrorCode) {if (AcceptNo> 4) return; if (Accept (servesocket [AcceptNo]! )) {// Receive request failed AFXMessageBox ("Accept Fail!", 12);} Else {// Receive request success servesocket [Acceptno] .Serveno = AcceptNo; Switch (acceptno) {// According to the sequence of reception, to the client Send a message Case 0: {Servesocket [AcceptNo] .send ("Message 0", 10); Break;} case 1: {servesocket [acceptno] .send ("Message 1", 10); Break;} case 2: { Servesocket [Acceptno] .send ("Message 2", 10); Break;} case 3: {servesocket [acceptno] .send ("Message 3", 10); Break;

} Case 4: {Servesocket [AcceptNo] .send ("Message 4", 10); Break;} default: Break;} // afxMessageBox ("Accept Client!", 14); AcceptNo ;} CasyncSocket :: Onaccept (NerrorCode );} Void MySocket :: OnRecEive (INT NERRORCODE) {if (Receive (RX_BUF, 100)) {// Re-issuings received by MessageBeep (0); AFXMessageBox; Send (rx_buf, 10);} Else {// Receive Error AFXMessageBox ("Receive Failed", 14); Return;} CasyncSocket :: OnRecEive (NerrorCode);} 3. Class Cchildview: Public CChildview: PUBLIC CCHILDVIEW: MYSOCKET SOCKET_ID; // Define Sockets ... protected: // {AFX_MSG (cchildview)} AFX_MSG void onpaint (); AFX_MSG Void onclient (); AFX_MSG VOID ONSERVER (); //}} AFX_MSG DECLARE_MESSAGE_MAP ()} 4. childview.cpp file relevant part BEGIN_MESSAGE_MAP (CChildView, CWnd) // {{AFX_MSG_MAP (CChildView) ON_WM_PAINT () ON_COMMAND (ID_CLIENT, OnClient) // set the program menu item ID_CLIENT client ON_COMMAND (ID_SERVER, OnServer) // Menu Item ID_Client Set the program to server //}} AFX_MSG_MAP END_MESSAGE_MAP () void cchildview :: onclient () {CClientDC DC (this); // Creat A socket socket_id.create (); dc.textout (200, "100," Connect ", 7); if (socket_id.connect (" 192.0.0.0 ") // server host IP address and port number DC.Textout (200, 120," Connect Fail! ", 13); Else Dc.Textout 200, 1220, "Connect Successful!", 18);} void cchildview :: ONSERVER () {cclientDC DC (this); // Create a defined socket socket_id.create (2000); // Assign a port ( 2000) //Socket_id.bind (2000,192.0.0.0 "); // port number and server host IP address. Different hosts are different.

转载请注明原文地址:https://www.9cbs.com/read-1680.html

New Post(0)