Caiyi9000 original transferred from: http://zhoumingbo.yeah.net
For a Windows network programming beginner, 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 implements 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 // Defines Network Event SockAddr_in ClientAddr; // Temporarily Store Client IP Address
// If you define your message mapping function, map the network event defined above to the process function // onnetEvent to the network event handler, which defines the on_message below; "NetWork_Event, OnNetEvent;
In the initialization function of the initialization network in your dialog box, the sub-function BOOL INITNETWORK () // initialization network {// initializes the TCP protocol BOOL RET = WSAStartup (MakeWord (2, 2), & WSADATA); if (RET! = 0) {MessageBox ("Initialization Solder Failed!"); Return False;}
// Create server-side socket Socket ServerSocket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (Serversocket == Invalid_Socket) {MessageBox ("Create a socket failed!"); CloseSocket (M_Socket); wsacleanup (); Return False;}
// bind to a local port sockaddr_in localaddr; localaddr.sin_family = AF_INET; localaddr.sin_port = htons (1688); localaddr.sin_addr.s_addr = 0; if (bind (serverSocket, (const struct sockaddr *) & localaddr, sizeof (SOCKADDR) == SOCKET_ERROR) {MessageBox ("Binding Address Failed!"); CloseSocket (M_Socket); wsacleanup (); Return False;}
// Register a network asynchronous event, m_hwnd is the handle of the application's main dialog or the main window Wsaasyncselect (ServerSocket, M_HWND, NetWork_Event, FD_ACCEPT | FD_CLOSE | FD_READ | FD_WRITE);
Listen (Serversocket, 5); // Set the listening mode
Return True;}
/ / Define the response function of the network event VOID OnNetEvent (WPARAM WPARAM, LPARAM LPARAM) {// Call the API function, get the network event type Ievent = WsagetSelectEvent (LPARAM);
// Get the client sleeve text psock = (socket) WPARAM;
Switch (ievent) {copy fd_accept: // Client connection request {onaccept ();
Break;} Case FD_Close: // Client Drops: {OnClose (PSock); Break;} Case FD_READ: // Network Packet Arrival Event {OnReceive (PSock); Break;} Case FD_WRITE: // Send Network Data Event {Onsend (psock); Break;} default: Break;}} Void onaccept (SOCET PSOCK) / / Response Client Connection Request Function {Int Len = SizeOf (SockAddr);
// Call the API function, accept the connection, and return a new socket // can also get the client's IP address socket clientsocket = accept (Serversocket, (Struct SockAddr *) & ClientAddr, & len);
/ / Register for the new Socket, pay attention to the Accept event IF (WsaasyncSelect (ClientSocket, M_HWND, IP_EVENT, FD_CLOSE | FD_READ | FD_WRITE) == Socket_ERROR) {MessageBox ("Register Asynchronous Event Failed!"); Return;}
/ / Self-editing function, save this client's related information: socket, // ip address, login time saveclientsocket (ClientSocket, ClientAddr, CurrentTimer);}
Void OnClose (SOCET PSOCK) {// The self-edged function, end communication with the corresponding client, release the corresponding resources and processes endClientSocket (PSock);
Void Onsend (SOCET PSOCK) {// Self-editing function, do some pre-processed HandleOnsend (PSock) when data is sent to the client.
Void OnRecEive (SOCET PSOCK) {RECV (...); // Call the API function, read the packets in the network buffer
// Self-editing function, encapsulate this packet and the client // ClientSocket to the client // ClientSocket into a network message buildnetMSG (...);
/ / Self-editing function, put this network message into a message queue, deal with SAVENETMSG (...) by the working thread; setEvent (...); // Trigger a work thread with event objects}
After the client logs in, the computer name will be sent to the server. After the server is connected, save 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.
Work Thread - Create and start a work thread when you initialize your application
AfxBeginthread (Workthread, this, thread_priority_normal); // this may be the handle of the application's master dialog or main window
Uint Workthread (LPVOID PPARAM) {While (1) {// Waiting for multiple events arriving int RET = WaitFormultiPleObject (...);
Switch (re) {copy object_0: {if (bnewnetmsg) / / View the network message queue has a new network message {readNetmsg (...); // reads Handlenetmsg (...) ); // Handling this network message} Break;} Case Object_0 1: {// Doing exit processing Break;} default: Break;
Return 0;}
When the client is single-thread, when the server is logged to the server, use the connection () function to send a request for the server; the client does not have an onaccept () function, but there is an 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.