[转] [Recommended] Windows Network Programming Classic Getting Started

xiaoxiao2021-03-06  113

[Recommended] Windows Network Programming Classic Getting Started

[Recommended] Windows Network Programming Classic Getting Started CAIYI9000 The original for a Windows network programming initiator, the following method is a classic entry. Beginners recommends not to use the class provided by the MFC, and use the Windows API to make a simple server and client, which helps to understand the Socket programming mechanism. For the sake of simplicity, the application is a MFC-based standard dialog.

Winsock is implemented with Windows API: (1) The server side has two threads: main thread - you need to write the following functions to implement #define network_event user_message 100 file: // Define Network Event SockAddr_in ClientAddr; File: // Temporarily Store Client IP address file: // ourselves to define message mapping functions, map the network events defined above to the process function file: // onnetEvent to the network event handler, which defines the on_message (network_event, onnetEvent); in your dialog Initialization function calls the sub-function BOOL INITNETWORK () file: // Initiation network {file: // Initialization network {file: // Initialization TCP protocol BOOL RET = WSAStartup (MakeWord (2, 2), & WSADATA); if (Ret! = 0 ) {MessageBox ("Initializing Socket Failed!"); Return False;} File: // Create Server End Tape Socket ServerSocket = Socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (Serversocket == Invalid_Socket) {MessageBox "Creating a socket failure!"); Closocket (m_socket); wsacleanup (); returnaf (); Return False;} file: // Bind to local port sockaddr_in localaddr; localaddr.sin_family = af_inet; locaDr.sin_port = htons (1688 ); localaddr.sin_addr.s_addr = 0; if (bind (serverSocket, (const struct sockaddr *) & localaddr, sizeof (sockaddr)) == SOCKET_ERROR) {MessageBox ( "bound address failed!"); closesocket (m_Socket); WSACLANUP (); RETURN FALSE;} File: // Register Network Asynchronous Event, M_HWnd is the handle of the application's master dialog or the main window WSaasyncSele CT (Serversocket, M_HWND, NetWork_Event, FD_ACCEPT | FD_CLOSE | FD_READ | FD_WRITE); Listen (ServerSocket, 5); file: // Sets Listening Mode Return True;} file: // Defines the response function of Network Event VOID OnNETEVENT (WPARAM WPARAM, LPARAM LPARAM) {file: // Call the API function to get the network event type int tent = wsagetSelectEvent (LPARAM); file: // Get the client cover of this event Socket Psock = (Socket) WPARAM; switch (Switch) IEvent) {copy fd_accept: file: // Client connection request {onaccept (); break;} case fd_close: file: // Client break Event: {onClose (psock); break;} case fd_read: file: / / Network packet reaches event {onreceive (psock); break;} case fd_write: file: // Send network data event {Onsend (psock); Break;} default: Break;

}}} Void onaccept (SOCET PSOCK) File: / / Respond to the client connection request function {int LEN = sizeof (socketdr); file: // call the API function, accept the connection, and return a new socket file: // can get the client's IP address SOCKET clientSocket = accept (serverSocket, (struct sockaddr *) & clientaddr, & len); file: // new socket registered asynchronous event, note that no Accept events if (WSAAsyncSelect (clientSocket, m_hWnd, IP_EVENT, FD_CLOSE | Fd_read | fd_write) == SOCKET_ERROR) {MessageBox ("Register Asynchronous Event Failed!"); Return;} File: // Self-editing function, save this client's related information: socket, // ip address, Landing time SaveclientSocket (ClientTimket, ClientDr, CurrentTimer); (SOCET PSOCK) {file: // Self-editing function, do some pre-processed handleonseONSEND (PSock) when data is issued to the client,} void onreceive (SOCET PSOCK) {RECV (...); file: // Call API Function, read out the packet file: // self-editing function in the network buffer, encapsulate this packet and the client file: // clientsocket of this data into a network message buildnetMSG (...); file: / / Self-editing function, put this network message into a message queue, deal with SAVENETMSG (...) by the working thread; set: file: // Trigger the work thread with the event object} After login , Immediately send your computer name to the server, and save it after receiving it. This allows the server to display all online client information, including: client computer name, IP address, login time, etc. Note: The client does not have an onaccept () function, but there is an onconnect () function. Working Thread - When your application is initialized, create and launch a work thread AfxBeginthread (Workthread, this, thread_priority_normal); file: // this might for the application's master dialog or main window handle Uint Workthread (LPVoid PParam) {While (1) {file: // Waiting for multiple events arrived int RET = WaitFormultipleObject (...); switch (re) {case object_0: {if (bnewnetmsg) file: // View network message queue has new network Message {readNetmsg (...); file: // If there is a new network message, read Handlenetmsg (...); file: // Handling this network message} Break;} case object_0 1: {file: // Do exit processing break;} default: Break;} return 0;} The client is a single thread, when the server is logged in, use the connect () function to send a request to the server; the client does not have an onaccept () function, but there is onConnect ( )function.

Preproreating during the onConnect () function; responds to the onRecEive () function and processes network data; in the onclose () function responds to the closing event of the server; when you do data in the onsend () function Prerequisites; if you want to realize online communication between the clients (ie, the so-called chat room), you can also make a multi-point to multi-point local area network multicast model model based on the UDP protocol. Talk to you, you first implement the above procedure. The above I / O asynchronous model is based on Windows-based message mechanism, and you can also use event models, overlapping models, or complete port models. It is recommended that you refer to the books such as the Windows Network Programming Guide. If you can be skilled on the above mechanism, you have already understood the mechanism of Winsock's online program, next you can make more exciting programming, not only can transfer normal data online, but also transmit voice, video data You can also do a chat room yourself, and you can share your results in the LAN in the laboratory. Author Blog:

http://blog.9cbs.net/huyoo/

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

New Post(0)