Windows socket programming TCP Example 3 (wsaasyncselect)

Source: Internet
Author: User
Tags htons

The wsaasyncselect model allows applications to receive network event notifications in the form of Windows messages. this model is set to adapt to the Windows Message Drive environment. Currently, many network applications with low performance requirements use the wsaasyncselect model. the csocket class in MFC also uses it.

The following example provides the same functions as the previous two articles (one of the two articles): the client connects to the server and sends data to the server. The server receives and outputs the data sent from the client. The server still processes multi-client connections in a single thread.

Server. cpp restart -----------------------------------------------------------------------------------------

1. Create a window in main but hide the window without calling showwindow. Because it is a control function, there is still a control function window.

2. initialize the Windows Socket library, create a socket, bind a socket, and listen to the socket in serversocketproc.

3. Process socket-related messages in window functions

4. When the client closes the socket through closesocket, the following fd_close event output is displayed: "fd_close"

Directly disabling the client will make wsagetselecterror (lparam) true, and the output will be: "wsagetselecterror get error"

# Include <windows. h ># include <iostream> using namespace STD; lresult callback wndproc (hwnd, uint, wparam, lparam); int serversocketproc (hwnd); # pragma comment (Lib, "ws2_32.lib ") # define wm_socket wm_user + 100 # define port_no 6000 # define backlog 10 // global variable socket gsocksrv; int main () {static tchar lpszappname [] = text ("testwin "); hwnd; MSG; wndclass WC; WC. style = cs_hredraw | cs_vredraw; WC. lpfnwndpr OC = wndproc; WC. cbclsextra = 0; WC. cbwndextra = 0; WC. hinstance = NULL; WC. hicon = loadicon (null, idi_application); WC. hcursor = loadcursor (null, idc_arrow); WC. hbrbackground = (hbrush) getstockobject (white_brush); WC. lpszmenuname = NULL; WC. lpszclassname = lpszappname; // register the window class if (! Registerclass (& WC) {MessageBox (null, text ("this program requires Windows NT! "), Lpszappname, mb_iconerror); Return 0;} // create the application Main Window hwnd = createwindow (lpszappname, text (" server "), ws_overlappedwindow, cw_usedefault, cw_usedefault, null, null); If (null = hwnd) {MessageBox (null, text ("createwindow failed. "), lpszappname, mb_iconerror); Return 0;} // create a socket service int ret = serversocketproc (hwnd); If (0! = RET) {MessageBox (null, text ("serversocketproc failed. "), lpszappname, mb_iconerror); Return 0;} // message loop while (getmessage (& MSG, null, 0, 0) {translatemessage (& MSG ); dispatchmessage (& MSG) ;}// clear resources ------ closesocket (gsocksrv); wsacleanup (); Return MSG. wparam;} // window procedure function // lresult callback wndproc (hwnd, uint message, wparam, lparam) {Switch (Message) {Case wm_socket: // process socket information {int re T; socket sock = wparam; // check whether an error occurs. If (wsagetselecterror (lparam) {closesocket (sock); cout <"wsagetselecterror get error" <Endl; if (sock = gsocksrv) {destroywindow (hwnd) ;}return 0 ;}// process the event switch (wsagetselectevent (lparam) {Case fd_accept: // The socket in the listener detects that a connection has entered {int Len = sizeof (sockaddr); sockaddr_in addrclient; socket sockconn = accept (sock, (sockaddr *) & addrclient, & Len ); if (invalid_socket = sockconn ){ Cout <"accept () failed:" <wsagetlasterror () <Endl; return 0 ;}cout <"New Connection Received:" <inet_ntoa (addrclient. sin_addr) <Endl; wsaasyncselect (sockconn, hwnd, wm_socket, fd_read | fd_write | fd_close);} break; Case fd_write :{} break; Case fd_read: {char recvbuffer [max_path] = {0}; ret = Recv (sock, recvbuffer, sizeof (recvbuffer), 0); If (ret = 0) {cout <"connection has been gracefully closed. "<en DL; closesocket (sock); Return 0;} else if (ret = socket_error) {cout <"connection has been closed ungracefully. "<Endl; closesocket (sock); Return 0;} cout <" receive data from client: "<recvbuffer <Endl;} break; Case fd_close: {cout <"fd_close" <Endl; closesocket (sock);} break ;}} break; Case wm_destroy: postquitmessage (0); Return 0;} return defwindowproc (hwnd, message, wparam, lparam);} in T serversocketproc (hwnd) {cout <"serversocketproc implements beg" <Endl; wsadata; int ret; Word wversionrequested = makeword (2, 2); socket socksrv; sockaddr_in addrsrv; handle hthread = NULL; // initialize Windows Socket ------ ret = wsastartup (wversionrequested, & wsadata); If (Ret! = 0) {cout <"wsastartup () failed:" <wsagetlasterror () <Endl; Return-1 ;}// create socket ------ socksrv = socket (af_inet, sock_stream, 0); If (invalid_socket = socksrv) {cout <"socket () failed:" <wsagetlasterror () <Endl; wsacleanup (); return-1;} gsocksrv = socksrv; addrsrv. sin_addr.s_un.s_addr = htonl (inaddr_any); addrsrv. sin_family = af_inet; addrsrv. sin_port = htons (port_no); // bind socket ------ ret = BIND (socksrv, (sockaddr *) & addrsrv, sizeof (sockaddr); If (socket_error = RET) {cout <"BIND () failed:" <wsagetlasterror () <Endl; closesocket (socksrv); wsacleanup (); Return-1 ;} // listen ------ ret = listen (socksrv, backlog); If (socket_error = RET) {cout <"Listen () failed:" <wsagetlasterror () <Endl; closesocket (socksrv); wsacleanup (); Return-1;} // wsaasyncselect ------ wsaasyncselect (socksrv, hwnd, wm_socket, fd_accept | fd_close ); cout <"serversocketproc ----------------------------------------- end" <Endl; cout <"server started ...... "<Endl; return 0 ;}

Client. cpp labels ---------------------------------------------------------------------------------------------------------

# Include <iostream> # include <windows. h> using namespace STD; # pragma comment (Lib, "ws2_32.lib") # define port_no 6000 # define srv_ip_addr "127.0.0.1" int main (INT argc, char * argv []) {int ret; wsadata; Word wversionrequested = makeword (2, 2); socket sockclient; sockaddr_in addrsrv; // initialize Windows Socket ------ ret = wsastartup (wversionrequested, & wsadata ); if (Ret! = 0) {cout <"wsastartup () failed:" <wsagetlasterror () <Endl; Return-1 ;}// create socket ------ sockclient = socket (af_inet, sock_stream, 0); If (invalid_socket = sockclient) {cout <"socket () failed:" <wsagetlasterror () <Endl; wsacleanup (); return-1;} addrsrv. sin_addr.s_un.s_addr = inet_addr (srv_ip_addr); addrsrv. sin_family = af_inet; addrsrv. sin_port = htons (port_no); // connection ------ ret = connect (sockclient, (sockaddr *) & addrsrv, sizeof (sockaddr); If (socket_error = RET) {cout <"Connect () failed:" <wsagetlasterror () <Endl; closesocket (sockclient); wsacleanup (); Return-1 ;} else {cout <"Connect () successfully. "<Endl;} // send data ------ char sendbuf [max_path] = {0}; while (1) {cin. getline (sendbuf, sizeof (sendbuf); If (strcmp (sendbuf, "exit") = 0) {break;} ret = Send (sockclient, sendbuf, strlen (sendbuf) + 1, 0); If (socket_error = RET) {cout <"Send () failed:" <wsagetlasterror () <Endl; closesocket (sockclient ); wsacleanup (); Return-1 ;}// clear resources ------- closesocket (sockclient); wsacleanup (); cout <"exit... "<Endl; return 0 ;}

Example image: Success :------------------------------------------------------------------------------------------------

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.