CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  1. #1
    Join Date
    Jul 2005
    Posts
    14

    Asynchronous Socket

    Maybe somebody have sample code where Asynchronous Socket was used?
    The best would be irc client ;].
    Thx

  2. #2
    Join Date
    May 2007
    Posts
    56

    Re: Asynchronous Socket

    This helped me getting started:
    http://www.gamedev.net/reference/art...rticle1297.asp

    Good luck.

  3. #3
    Join Date
    Jul 2005
    Posts
    14

    Re: Asynchronous Socket

    At start thx for quick response
    I saw this tutorial.
    Code:
    #include <vcl.h>
    #include <iostream.h>
    #include <winsock.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    
            SOCKET sock;
            SOCKADDR_IN sockParam;
            struct hostent *googleIP;
    const char g_szClassName[] = "myWindowClass";
    
    // Step 4: the Window Procedure
    LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
    {
        switch(msg)
        {
            case WM_USER:
             {
    	        switch (WSAGETSELECTEVENT(lParam))
                 {
            case FD_ACCEPT:
    
            break;
            case FD_READ:
    	cout<<"Something for read";
    
            break;
            case FD_CONNECT:
             cout<<"connected";
            break;
            case FD_WRITE:
    
            break;
                    }
    
            }
    
    
    
    
            case WM_CLOSE:
    
            break;
            case WM_DESTROY:
    
            break;
            case WM_KEYDOWN:
    
    
            break;
    
            default:
                return DefWindowProc(hwnd, msg, wParam, lParam);
        }
        return 0;
    }
    
    int  main()
    {
        WNDCLASSEX wc;
        HWND hwnd;
        MSG Msg;
    
            WORD wVersionRequested;
            WSADATA wsaData;
    
    
        int error_code = 0;
    int rcv        = 0;
    
    String query = "GET /search?hl=en&q=";
    query += "evil"; //argv[1]
    query += " HTTP/1.0\r\nHost:www.google.com\r\nAccept: */*\r\nUser-Agent: Mozilla/5.0\r\n\r\n";
    
    
    
    
    
        //Step 1: Registering the Window Class
        wc.cbSize        = sizeof(WNDCLASSEX);
        wc.style         = 0;
        wc.lpfnWndProc   = WndProc;
        wc.cbClsExtra    = 0;
        wc.cbWndExtra    = 0;
        wc.hInstance     = GetModuleHandleA(0);
        wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
        wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
        wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
        wc.lpszMenuName  = NULL;
        wc.lpszClassName = g_szClassName;
        wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);
    
        if(!RegisterClassEx(&wc))
        {
            MessageBox(NULL, "Window Registration Failed!", "Error!",
                MB_ICONEXCLAMATION | MB_OK);
            return 0;
        }
    
        // Step 2: Creating the Window
        hwnd = CreateWindowEx(
            WS_EX_CLIENTEDGE,
            g_szClassName,
            "The title of my window",
            WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
            HWND_MESSAGE, //set Only-Message Window
             NULL, GetModuleHandleA(0), NULL);
    
        if(hwnd == NULL)
        {
            MessageBox(NULL, "Window Creation Failed!", "Error!",
                MB_ICONEXCLAMATION | MB_OK);
            return 0;
        }
          wVersionRequested=MAKEWORD(2,2);
    WSAStartup(wVersionRequested,&wsaData);
    
    
    
       sock = socket(AF_INET,
    		 SOCK_STREAM,
    		 IPPROTO_TCP);
    
    
        /*Set Parameters*/
        googleIP = gethostbyname("google.com");
    
    
                 ZeroMemory(&sockParam,sizeof(sockParam));
                 sockParam.sin_family        = AF_INET;
                 sockParam.sin_addr.s_addr   = ((struct in_addr *)(googleIP->h_addr))->s_addr;
                 sockParam.sin_port          = htons(80);
    
                     connect(sock,
                            (sockaddr*)&sockParam,
                            sizeof(sockParam));
    
    
    
    
    
    
    
         cout<<"Your query is: "<<query.c_str();
        WSAAsyncSelect(sock,hwnd,WM_USER,FD_CONNECT|FD_READ|FD_WRITE|FD_ACCEPT);
        ShowWindow(hwnd, SW_SHOW);
        UpdateWindow(hwnd);
    
        // Step 3: The Message Loop
        while(GetMessage(&Msg, NULL, 0, 0) > 0)
        {
            TranslateMessage(&Msg);
            DispatchMessage(&Msg);
        }
        return Msg.wParam;
    }
    Can you tell me why this code dosn't work correctly? ;/
    Last edited by Termor; July 26th, 2007 at 03:33 PM. Reason: add new item

  4. #4
    Join Date
    May 2007
    Posts
    56

    Re: Asynchronous Socket

    Whats the problam your getting?

  5. #5
    Join Date
    Jul 2005
    Posts
    14

    Re: Asynchronous Socket

    i'm little update my code
    Code:
    //---------------------------------------------------------------------------
    
    #include <vcl.h>
    #include <iostream.h>
    #include <winsock.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    
            SOCKET sock;
            SOCKADDR_IN sockParam;
            struct hostent *googleIP;
            const char g_szClassName[] = "myWindowClass";
            char buf[1000];
    
    String query = "GET /search?hl=en&q=evil HTTP/1.0\r\nHost:www.google.com\r\nAccept: */*\r\nUser-Agent: Mozilla/5.0\r\n\r\n";
    
    // Step 4: the Window Procedure
    LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
    {
        switch(msg)
        {
            case WM_USER:
             {
    	        switch (WSAGETSELECTEVENT(lParam))
                 {
            case FD_ACCEPT:
    
            break;
            case FD_READ:
            recv(sock,buf,sizeof(buf),0);
    
    	cout<<buf;
    
            break;
            case FD_CONNECT:
             cout<<"connected";
            break;
            case FD_WRITE:
    
            break;
                    }
    
            }
    
            case WM_CLOSE:
    
            break;
            case WM_DESTROY:
    
            break;
            case WM_KEYDOWN:
             {
             send(sock,query.c_str(),query.Length(),0);
              }
            break;
    
            default:
                return DefWindowProc(hwnd, msg, wParam, lParam);
        }
        return 0;
    }
    
    int  main()
    {
        WNDCLASSEX wc;
        HWND hwnd;
        MSG Msg;
    
            WORD wVersionRequested;
            WSADATA wsaData;
    
    
    
        //Step 1: Registering the Window Class
        wc.cbSize        = sizeof(WNDCLASSEX);
        wc.style         = 0;
        wc.lpfnWndProc   = WndProc;
        wc.cbClsExtra    = 0;
        wc.cbWndExtra    = 0;
        wc.hInstance     = GetModuleHandleA(0);
        wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
        wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
        wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
        wc.lpszMenuName  = NULL;
        wc.lpszClassName = g_szClassName;
        wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);
    
        if(!RegisterClassEx(&wc))
        {
            MessageBox(NULL, "Window Registration Failed!", "Error!",
                MB_ICONEXCLAMATION | MB_OK);
            return 0;
        }
    
        // Step 2: Creating the Window
        hwnd = CreateWindowEx(
            WS_EX_CLIENTEDGE,
            g_szClassName,
            "The title of my window",
            WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
            HWND_MESSAGE,//this is Target Point!!!
             NULL, GetModuleHandleA(0), NULL);
    
        if(hwnd == NULL)
        {
            MessageBox(NULL, "Window Creation Failed!", "Error!",
                MB_ICONEXCLAMATION | MB_OK);
            return 0;
        }
          wVersionRequested=MAKEWORD(2,2);
    WSAStartup(wVersionRequested,&wsaData);
    
    
    
       sock = socket(AF_INET,
    		 SOCK_STREAM,
    		 IPPROTO_TCP);
    
    
        /*Set Parameters*/
        googleIP = gethostbyname("google.com");
    
    
                 ZeroMemory(&sockParam,sizeof(sockParam));
                 sockParam.sin_family        = AF_INET;
                 sockParam.sin_addr.s_addr   = ((struct in_addr *)(googleIP->h_addr))->s_addr;
                 sockParam.sin_port          = htons(80);
    
                     connect(sock,
                            (sockaddr*)&sockParam,
                            sizeof(sockParam));
    
    
        cout<<query.c_str();
    
        WSAAsyncSelect(sock,hwnd,WM_USER,FD_CONNECT|FD_READ|FD_WRITE|FD_ACCEPT);
        ShowWindow(hwnd, SW_SHOW);
        UpdateWindow(hwnd);
    
        // Step 3: The Message Loop
        while(GetMessage(&Msg, NULL, 0, 0) > 0)
        {
            TranslateMessage(&Msg);
            DispatchMessage(&Msg);
        }
        return Msg.wParam;
    }
    Every thing is ok when i set NULL on hWndParent in CreateWindowEx then i see the window(of course i don't want see it).So i can hit any key and send function is executed.

    Problem is when hWndParent is set to HWND_MESSAGE ,then my application don't respond for key hit.

    I think that i must send i.e WM_KEYDOWN message to this windows
    via SendMessage?

  6. #6
    Join Date
    Nov 2002
    Location
    California
    Posts
    4,556

    Re: Asynchronous Socket

    Tell us what do you think this code is supposed to do. Then tell us what the code is actually doing.

    Frankly, it's very odd code. It sends an HTTP GET request when you press a key, but the way it's coded, it's doubtful that it will ever get the response (i.e., the code under FD_READ is probably never triggered). Where did this code come from?

    Mike

  7. #7
    Join Date
    May 2007
    Posts
    56

    Re: Asynchronous Socket

    Sending a WM_KEYDOWN suppose to trigger it, but why do that? I mean why make a invisible window just to send and recive data?

  8. #8
    Join Date
    Nov 2002
    Location
    California
    Posts
    4,556

    Re: Asynchronous Socket

    ... why make a invisible window just to send and recive data
    That's how asynchronous sockets work in Windows. The winsock stack posts a message to the window of your choice, when a socket event occurs. For example, when data arrives, an FD_READ notification is posted to the window that you specified in the call to WSAAsyncSelect().

    It's not required that the window is hidden. If you are writing a "from scratch" API program, then the window is often the main GUI window.

    Most frameworks, however, create one new hidden window for each new socket. This tends to be more object-oriented, and has other benefits too.

    There are other ways to work with sockets in a non-blocking way. The WSAAsyncSelect() method is elegant in a windowing environment, since it converts socket events into ordinary Windows messages, thereby serializing socket events into the stream of other events that the application is handling.

    But other ways do, in fact, exist. For example, select-based architectures, event-based architectures (using WSAEventSelect()), and I/O completion ports. It all depends on what you want to do.

    Mike

  9. #9
    Join Date
    Jul 2005
    Posts
    14

    Re: Asynchronous Socket

    Ok,i changed function WSAAsyncSelect to WSAEventSelect and work very nice ;]..btw:thx for this advise .
    But i little problem.Please look on code:
    Code:
     DWORD WINAPI start_thread(LPVOID thread_data)
     {
        SOCKET sock=(SOCKET&)thread_data;
        WSAEVENT hEventObject = WSA_INVALID_EVENT;
        hEventObject = WSACreateEvent();
        WSANETWORKEVENTS hConnectEvent;
    
        char buf[1024];
    
        WSAEventSelect(sock,hEventObject,FD_READ | FD_CLOSE);
    
            while(hWatku)
             {
                int nReturnCode = WSAWaitForMultipleEvents(1, &hEventObject,
                                                           FALSE, INFINITE, FALSE);
    
                    WSAEnumNetworkEvents(sock ,(unsigned long)&hConnectEvent,&hConnectEvent);
    
    		if ( hConnectEvent.lNetworkEvents & FD_READ)
    		{
    
    				recv(sock,buf,sizeof(buf),0);
                                    cout<<buf<<endl;
    
                    }
    		if (hConnectEvent.lNetworkEvents & FD_CLOSE)
    		{
    			shutdown(sock,FD_READ|FD_CLOSE);
    			closesocket(sock);
    			ExitThread(0);
    		}
    
             }
    
    
        return 0;
     }
    this condition
    Code:
    	if ( hConnectEvent.lNetworkEvents & FD_READ)
    is always true ;/.
    i was trying also :
    Code:
    if ( hConnectEvent.lNetworkEvents & FD_READ &&  hConnectEvent.iErrorCode[FD_READ_BIT] == 0)
    but this condition is always false ;/.
    What is wrong with condition ?

  10. #10
    Join Date
    Jul 2005
    Posts
    14

    Re: Asynchronous Socket

    Ok, i found the error;]
    Code:
    WSAEnumNetworkEvents(sock ,hEventObject,&hConnectEvent);
    second variable was not correct in this function.

  11. #11
    Join Date
    Mar 2004
    Location
    (Upper-) Austria
    Posts
    2,899

    Re: Asynchronous Socket

    [ Moved Thread ]
    I am not offering technical guidiance via email or IM
    Come on share your photo with us! CG members photo album!
    Use the Code Tags!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured