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 file: // Define Network Event SockAddr_in ClientAddr; File: // Temporarily Store Client IP Address File: // To define the message mapping function, map the network event defined above to the process function file: // OnNetEvent handles the network event handler, it defines the on_message (NetWork_Event, OnNETEVEN) below;
In the initialization function of the initialization network in your dialog box, the subunipers () file: // Initialization Network {file: // Initialize the TCP protocol BOOL RET = WSAStartup (MakeWord (2, 2), & WSADATA); IF (RET! = 0) {MessageBox ("Initializing Solder Failed!"); Return False;
File: // 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;}
file: // 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;}
File: // Register a network asynchronous event, m_hwnd is the handle of the application's master dialog or the main window WSaasyncselect (Serversocket, M_HWND, Network_Event, FD_ACCEPT | FD_CLOSE | FD_READ | FD_WRITE);
Listen (Serversocket, 5); file: // Sets the listening mode Return True;}
File: / / Define the response function void onnet (WPARAM WPARAM, LPARAM LPARAM) {file: // Call the API function, get the network event type int = wsagetSelectEvent (LPARAM); file: // get this event Terrace Socket Psock = (socket) WPARM; SWITCH (IEvent) {CASE FD_ACCEPT: File: // Client Connection Request {onaccept ();
Break;} case fd_close: File: // Client DC Event: {OnClose (PSock); Break;} Case FD_READ: File: // Network Packet Arrival Event {OnReceive (PSock); Break;} Case FD_WRITE: File : // Send network data event {Onsend (psock); Break;};
Void onaccept (SOCET PSOCK) File: / / Response Client Connection Request Function {INT LEN = SizeOf (SockAddr);
File: // Call the API function, accept the connection, and return a new socket file: // You can also get the client's IP address Socket ClientSocket = Accept (Serversocket, (Struct SockAddr *) & Clientaddr, & Len);
File: // 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 ("Registered Asynchronous Event Failed!"); Return; } File: // Self-editing function, save this client's related information: socket, // ip address, login time SaveclientSocket (ClientTimket, CLIENTDR, CURRENTTIMER);
Void OnClose (SOCET PSOCK) {file: // The self-edged function, end communication with the corresponding client, release the corresponding resources and proceed for the corresponding processing EndClientSocket (PSock);
Void Onsend (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 the API function, read out the packet file: // self-edged function in the network buffer, and send this packet and the client that issues this data File: // ClientSocket package 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 a work thread with event object} After logging in, then send your computer name 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); file: // this may be the handle of the application's primary dialog or main window
Uint Workthread (LPVOID PPARAM) {While (1) {file: // Waiting for multiple events arrival int RET = WaitFormultiPleObject (...); switch (re) {copy object_0: {if (bnewnetmsg) file: // View network message Does the queue have new network messages {readNetmsg (...); file: // reads 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 and logs to the server, and the server is used to send a request with the connect () function; 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 Pretreatment;
If you want to realize online communication between the clients (ie, the so-called chat room), you can also make a multi-point multi-point local area network multicast model model based on the UDP protocol, and later Talk, you first implement the above program. 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.