[C++]Window Problem

Started by
8 comments, last by Mike nl 15 years, 8 months ago
I am starting to make a server for a project, and to test my skills as a programmer(Gotta start somewhere) I've read Forgers-Win32 Tutorial on Win32 API. I got my Winsock2 working perfectly fine in a Console Program it connects etc etc. Now I've created a Simple Window with some help from Forgers-Win32 An I attepmpted to intergrade the Winsock2 into the simple window, but every time I go to run the program it never shows up any help?? Server Code
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>



#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(void) 
{
    WSADATA wsaData;
    SOCKET ListenSocket = INVALID_SOCKET,
           ClientSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
                    hints;
    char recvbuf[DEFAULT_BUFLEN];
    int iResult, iSendResult;
    int recvbuflen = DEFAULT_BUFLEN;
    

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Create a SOCKET for connecting to server
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("socket failed: %ld\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // Setup the TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
        printf("listen failed: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // No longer need server socket
    closesocket(ListenSocket);

    // Receive until the peer shuts down the connection
    do {

        iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
        if (iResult > 0) {
            printf("Bytes received: %d\n", iResult);

        // Echo the buffer back to the sender
            iSendResult = send( ClientSocket, recvbuf, iResult, 0 );
            if (iSendResult == SOCKET_ERROR) {
                printf("send failed: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }
            printf("Bytes sent: %d\n", iSendResult);
        }
        else if (iResult == 0)
            printf("Connection closing...\n");
        else  {
            printf("recv failed: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }

    } while (iResult > 0);

    // shutdown the connection since we're done
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

    return 0;
}
Window Code
#include <windows.h>

const char g_szClassName[] = "Ever Life 0.0.0.1";

//step 4: the Window Procedure
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
               case WM_CLOSE:
                    DestroyWindow(hwnd);
               break;
               case WM_DESTROY:
                    PostQuitMessage(0);
               break;
               default:
                       return DefWindowProc(hwnd, msg, wParam, lParam);
          }
          return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;
    
    //Step 1: Registering the Window Class
    wc.cbSize         = sizeof(WNDCLASSEX);
    wc.style          = 0;
    wc.lpfnWndProc    = WndProc;
    wc.cbClsExtra     = 0;
    wc.cbWndExtra = 0;
wc.hInstance = hInstance;
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,
"Ever Life 0.0.0.1",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
NULL, NULL, hInstance, NULL);
if(hwnd == NULL)
{
MessageBox(NULL, "Window Creation Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// Step 3: The Message Loop
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
So can someone help me out? [Edited by - ARC inc on August 19, 2008 12:53:52 PM]
Advertisement
Are you trying to compile both chunks of code into one application? If so, only main() or WinMain() will be called (Depending on if you're building a console or Win32 application).

if you're only compiling the second code snippet, does the code enter the message loop? Check the debugger to find out.
The window code (seperately, like Evil Steve said) works fine for me.

That said, some tips:

  • Use [ source ] tags to put code in your post (you can change it now with Edit).

  • You can pass NULL for the MessageBox's caption, and Windows will put the locale specific version of "Error" there.

  • hIconSm can be NULL as well, it'll use hIcon in that case.

  • Don't return 0 on error. 0 typically means that everything went OK.

  • GetMessage returns a BOOL, test it as such: while (GetMessage(..))

Million-to-one chances occur nine times out of ten!
Sorry ArcInc the code given for the window program seems to be correct but I don't understand : do you mean that the window isn't displayed ?
If you have problem with the window program to attempt to connect to the server program, I recommend you to implement a multithreading architecture with a thread function listening the sockets opened.
I recommend to read Charles Petzold's book about win32 programing ( Microsoft Press ).
Window sockets topic is covered in one chapter
Quote:Original post by Mike nl
GetMessage returns a BOOL, test it as such: while (GetMessage(..))
Actually, GetMessage is a bit weird. Docs:
Quote:Warning

Because the return value can be nonzero, zero, or -1, avoid code like this:
while (GetMessage( lpMsg, hWnd, 0, 0))


I didn't know about the NULL title for a message box, that's something for me to remember [smile]
Quote:Original post by Evil Steve
Quote:Original post by Mike nl
GetMessage returns a BOOL, test it as such: while (GetMessage(..))
Actually, GetMessage is a bit weird. Docs:
Quote:Warning

Because the return value can be nonzero, zero, or -1, avoid code like this:
while (GetMessage( lpMsg, hWnd, 0, 0))


Whoops, indeed. I once noticed this, applied it, and then forgot it I think. Either way, != 0 instead of > 0 is preferred then.

Million-to-one chances occur nine times out of ten!
Quote:Original post by Mike nl
Either way, != 0 instead of > 0 is preferred then.


But (-1 != 0) == true while (-1 > 0) == false...
I guess I need to explain what is going on

I make the Window(which works fine I know) I make the Winsock2 which works fine also.

But I want to put them together the Window is a C code(For some reason it wont work in C++ probably not adding the right C++ Libs) An add the Winsock2 to it so it will Print out all the server inforamtion onto the Window like in a txt formate like it would in a consle program. But all I get is 2 windows 1 window is my window I created with the codding an there other one is the Console i've checked I am using Win32 GUI thingy with Dev-C++ an have linked in MicroSoft SDK Include folder and the Win2_s2.lib(think thats what it is)
You have two separate programs. How do you expect them to work together?

You'll need to add the Winsock code (with the appropriate changes) to the Windows application for this to work.
Quote:Original post by Gage64
Quote:Original post by Mike nl
Either way, != 0 instead of > 0 is preferred then.


But (-1 != 0) == true while (-1 > 0) == false...


Exactly, and the former is way to go, according to MSDN.

Quote:Original post by ARC inc
I guess I need to explain what is going on

I make the Window(which works fine I know) I make the Winsock2 which works fine also.

But I want to put them together the Window is a C code(For some reason it wont work in C++ probably not adding the right C++ Libs) An add the Winsock2 to it so it will Print out all the server inforamtion onto the Window like in a txt formate like it would in a consle program. But all I get is 2 windows 1 window is my window I created with the codding an there other one is the Console i've checked I am using Win32 GUI thingy with Dev-C++ an have linked in MicroSoft SDK Include folder and the Win2_s2.lib(think thats what it is)


It still sounds as if you're having both codes in the same file or project. If that is the case, you have two entry points (main and WinMain) and only one will be called.

From your description it seems as if you magically expect these two programs to work together. That when you printf() in the server, the output shows up in the window of the window program. This does not work this way.

You should have two executables. One, which is the server process (with a console), and one which is the window process (without console).

You can have the server running in the window program as well, by using asynchronous sockets, or using threads. But you'll obviously need to seriously rewrite your code for that.

If I understand you wrong, please clarify. Clearly.
Million-to-one chances occur nine times out of ten!

This topic is closed to new replies.

Advertisement