Link to home
Start Free TrialLog in
Avatar of turbot_yu
turbot_yuFlag for Singapore

asked on

Compile Error

Hi Experts,

I added the following lines into my code and compile then has errors.
May you give any suggestion?

Need I add more include .h file or something else?

Thank and Regards,

Turbot

    SOCKET m_hListeningSocket;
    WSAEVENT m_hAcceptEvent;
    HANDLE m_hListeningThread;
    HANDLE m_hStopListenEvent;

error code

Compiling...
try4Dlg.cpp
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try4\try4Dlg.cpp(65) : error C2065: 'WSAEVENT' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try4\try4Dlg.cpp(65) : error C2146: syntax error : missing ';' before identifier 'm_hAcceptEvent'
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try4\try4Dlg.cpp(65) : error C2065: 'm_hAcceptEvent' : undeclared identifier
Error executing cl.exe.

try4Dlg.obj - 3 error(s), 0 warning(s)

Avatar of AlexFM
AlexFM

#include <winsock2.h>
Avatar of turbot_yu

ASKER

then get more error, totally 57

--------------------Configuration: try4 - Win32 Debug--------------------
Compiling...
try4Dlg.cpp
c:\program files\microsoft platform sdk\include\winsock2.h(112) : error C2011: 'fd_set' : 'struct' type redefinition
c:\program files\microsoft platform sdk\include\winsock2.h(147) : warning C4005: 'FD_SET' : macro redefinition
        c:\program files\microsoft platform sdk\include\winsock.h(88) : see previous definition of 'FD_SET'
c:\program files\microsoft platform sdk\include\winsock2.h(156) : error C2011: 'timeval' : 'struct' type redefinition
c:\program files\microsoft platform sdk\include\winsock2.h(212) : error C2011: 'hostent' : 'struct' type redefinition
c:\program files\microsoft platform sdk\include\winsock2.h(225) : error C2011: 'netent' : 'struct' type redefinition
c:\program files\microsoft platform sdk\include\winsock2.h(232) : error C2011: 'servent' : 'struct' type redefinition
c:\program files\microsoft platform sdk\include\winsock2.h(244) : error C2011: 'protoent' : 'struct' type redefinition
c:\program files\microsoft platform sdk\include\winsock2.h(400) : error C2011: 'sockaddr_in' : 'struct' type redefinition
c:\program files\microsoft platform sdk\include\winsock2.h(410) : error C2011: 'WSAData' : 'struct' type redefinition
c:\program files\microsoft platform sdk\include\winsock2.h(470) : warning C4005: 'SO_DONTLINGER' : macro redefinition
        c:\program files\microsoft platform sdk\include\winsock.h(411) : see previous definition of 'SO_DONTLINGER'
c:\program files\microsoft platform sdk\include\winsock2.h(527) : warning C4005: 'AF_IPX' : macro redefinition
        c:\program files\microsoft platform sdk\include\winsock.h(469) : see previous definition of 'AF_IPX'
c:\program files\microsoft platform sdk\include\winsock2.h(555) : warning C4005: 'AF_MAX' : macro redefinition
        c:\program files\microsoft platform sdk\include\winsock.h(488) : see previous definition of 'AF_MAX'
c:\program files\microsoft platform sdk\include\winsock2.h(561) : error C2011: 'sockaddr' : 'struct' type redefinition
c:\program files\microsoft platform sdk\include\winsock2.h(601) : error C2011: 'sockproto' : 'struct' type redefinition
c:\program files\microsoft platform sdk\include\winsock2.h(640) : error C2011: 'linger' : 'struct' type redefinition
c:\program files\microsoft platform sdk\include\winsock2.h(653) : warning C4005: 'SOMAXCONN' : macro redefinition
        c:\program files\microsoft platform sdk\include\winsock.h(553) : see previous definition of 'SOMAXCONN'
c:\program files\microsoft platform sdk\include\winsock2.h(679) : warning C4005: 'FD_READ' : macro redefinition
        c:\program files\microsoft platform sdk\include\winsock.h(571) : see previous definition of 'FD_READ'
c:\program files\microsoft platform sdk\include\winsock2.h(682) : warning C4005: 'FD_WRITE' : macro redefinition
turbot_yu, you are trying to reproduce class from the code from one of my answers. The code shows how to listen for connections and accept them. Result of accepting connection is socket which talks with specific client. This code already exists in your current application, you can copy from here. In your first post related to the problem you have code which looks like this:

SOCKET s = accept(...);
// talk with client using socket s

You can see such place in OnAccept function of me class. Copy your existing code there, and you have something to begin with. I can post the whole code of my class, but it contains a lot of unnecessary stuff which you cannot use, I don't think this will help.
Don't include winsock.h
There is not winsock.h in it.

I build a class as below also with a cpp named CServerSocket and with main entrance, but always has problem when compile them, any suggestion?

CServerSocket.h
#include <winsock2.h>
#include <afxsock.h>

class CServerSocket  
{
   //....

    SOCKET m_hListeningSocket;
    WSAEVENT m_hAcceptEvent;
    HANDLE m_hListeningThread;
    HANDLE m_hStopListenEvent;

public:

      void Initialize(int nPort);
      unsigned ListenThreadProc(LPVOID lpVoid);
      void ListenThreadFunction();
      void Cleanup();
      BOOL OnAccept(int nErrorCode);
};
////////////////////////////////////
CServerSocket.cpp

#include "CServerSocket.h"

// this is static function
unsigned CServerSocket::ListenThreadProc(LPVOID lpVoid)
{
    CServerSocket* p  = (CServerSocket*) lpVoid;
    p->ListenThreadFunction();

    return 0;
}

void CServerSocket::ListenThreadFunction()
{
    WSANETWORKEVENTS events;
    DWORD dwResult;
    int nError;
    BOOL bContinue = TRUE;

    HANDLE hEvents[2];
    hEvents[0] = m_hAcceptEvent;
    hEvents[1] = m_hStopListenEvent;

    PostLogMessage(_T("ListenThreadFunction started"));

    while ( bContinue )
    {
        // Wait for asynchronous socket notification (see WSAEventSelect call)
        // and our own stop event

        dwResult = WSAWaitForMultipleEvents(
            2,
            hEvents,
            FALSE,
            INFINITE,
            FALSE);

        nError = WSAGetLastError();
       
        switch ( dwResult )
        {
        case WAIT_OBJECT_0:
            // m_hAcceptEvent event is signaled, new client is connected

            dwResult = WSAEnumNetworkEvents(m_hListeningSocket, m_hAcceptEvent, &events);  // get event type

            nError = WSAGetLastError();

            WSAResetEvent(m_hAcceptEvent);

            if ( dwResult == SOCKET_ERROR )
            {
                PostLogMessage(_T("Error calling WSAEnumNetworkEvents"));
                PrintErrorDescription(nError);
                bContinue = FALSE;
                break;
            }

            // handle signaled network events (we sobscribed to only one - FD_ACCEPT)

            if ( events.lNetworkEvents & FD_ACCEPT )
            {
                // Handle Accept network event. If function returns FALSE (failed), exit
                if ( ! OnAccept(events.iErrorCode[FD_ACCEPT_BIT]) )
                {
                    bContinue = FALSE;
                    break;
                }
            }

            break;

        case WAIT_OBJECT_0 + 1:
            // m_hStopListenEvent is signaled
            bContinue = FALSE;
            break;

        default:
            PostLogMessage(_T("Error calling WSAWaitForMultipleEvents"));
            PrintErrorDescription(nError);
            bContinue = FALSE;
            break;
        }

    }

    PostLogMessage(_T("ListenThreadFunction finished"));
}

void CServerSocket::Cleanup()
{
    int i;
    m_bClosed = TRUE;

    if ( m_hListeningThread )
    {
        // stop listening thread
        SetEvent(m_hStopListenEvent);

        if ( WaitForSingleObject(m_hListeningThread, 3000) != WAIT_OBJECT_0 )
        {
            TerminateThread(m_hListeningThread, 0);
            TRACE(_T("Listening thread is terminated\n"));
        }

        CloseHandle(m_hListeningThread);
    }

    // release events
    if ( m_hStopListenEvent )
    {
        CloseHandle(m_hStopListenEvent);
    }

    if ( m_hAcceptEvent != WSA_INVALID_EVENT )
    {
        WSACloseEvent(m_hAcceptEvent);
    }

    // close listening socket
    if ( m_hListeningSocket != INVALID_SOCKET )
    {
        closesocket(m_hListeningSocket);
    }

    }

    // Close completion port
    if ( m_hCompletionPort )
    {
        CloseHandle(m_hCompletionPort);
    }

    // Sockets cleanup
    if ( m_bInitialized )
        WSACleanup();
}

BOOL CServerSocket::OnAccept(int nErrorCode)
{
    int nResult;
    int nError;

    if ( nErrorCode != 0 )
    {
        PostLogMessage(_T("Accept event error"));
        PrintErrorDescription(nErrorCode);
        return FALSE;
    }

    PostLogMessage(_T("Client connected"));

    // accept new connection
    SOCKADDR_IN SockAddr;           // gets information about client
    SOCKET clientSocket;
    int nAddrLen = sizeof(SOCKADDR_IN);

    clientSocket = accept(m_hListeningSocket,
                          (LPSOCKADDR)&SockAddr,
                          &nAddrLen);

    nError = WSAGetLastError();

    if ( clientSocket == INVALID_SOCKET )
    {
        PostLogMessage(_T("accept function failed"));
        PrintErrorDescription(nError);
        return TRUE;
    }

    // work with clientSocket here, but don't keep caller and return quickly.
    // possibly you need to create thread for client socket and return.
}
/////////////////////////////////////////////////////////////
For the main program

      CDialog::OnInitDialog();

      // Set the icon for this dialog.  The framework does this automatically
      //  when the application's main window is not a dialog
      SetIcon(m_hIcon, TRUE);                  // Set big icon
      SetIcon(m_hIcon, FALSE);            // Set small icon
      
      // TODO: Add extra initialization here
    unsigned int dwThreadID;

    // initialize Windows Sockets
    WSADATA wsaData;
    int nResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    int nError = WSAGetLastError();

    if ( nResult != 0 )     // OK
    {
        PostLogMessage(_T("Winsock initialization failed"));
        PrintErrorDescription(nError);
        return;
    }

    m_bInitialized = TRUE;
    PostLogMessage(_T("Winsock initialization succeeded"));

    // create listening socket
    m_hListeningSocket = WSASocket(
        AF_INET,
        SOCK_STREAM,
        0,
        NULL,
        0,
        WSA_FLAG_OVERLAPPED);         // non-blocking

    nError = WSAGetLastError();

    if ( m_hListeningSocket == INVALID_SOCKET )
    {
        PostLogMessage(_T("Creating of listening socket failed"));
        PrintErrorDescription(nError);
        return;
    }

    // create Accept event
    m_hAcceptEvent = WSACreateEvent();
    nError = WSAGetLastError();

    if ( m_hAcceptEvent == WSA_INVALID_EVENT )
    {
        PostLogMessage(_T("Creating of Accept event failed"));
        PrintErrorDescription(nError);
        return;
    }

    // Associate FD_ACCEPT socket event with m_hAcceptEvent. Now m_hAcceptEvent
    // will be signaled when new client request is received
    // by m_hListeningSocket.
    // m_hAcceptEvent is signaled when accept() may be called whith
    // expectation if immidiate success.
    nResult = WSAEventSelect(m_hListeningSocket,
                             m_hAcceptEvent,
                             FD_ACCEPT);
   
    if ( nResult == SOCKET_ERROR )
    {
        PostLogMessage(_T("WSAEventSelect failed"));
        PrintErrorDescription(nError);
        return;
    }

    // fill SOCKADDR_IN structure
    SOCKADDR_IN     saServer;      

    saServer.sin_port = htons((unsigned short)nPort);
    saServer.sin_family = AF_INET;
    saServer.sin_addr.s_addr = INADDR_ANY;

    // bind SOCKADDR_IN to the listening socket
    nResult = bind(m_hListeningSocket,
                   (LPSOCKADDR)&saServer,
                   sizeof(struct sockaddr));

    if ( nResult == SOCKET_ERROR )
    {
        PostLogMessage(_T("bind function failed"));
        PrintErrorDescription(nError);
        return;
    }

    // Start listening
    nResult = listen(m_hListeningSocket, SOMAXCONN);

    if ( nResult == SOCKET_ERROR )
    {
        PostLogMessage(_T("listen function failed"));
        PrintErrorDescription(nError);
        return;
    }

    // create Stop Listening Thread event
    m_hStopListenEvent = CreateEvent(NULL, TRUE, FALSE, NULL);  // manually reset, initially unsignaled

    if ( ! m_hStopListenEvent )
    {
        PostLogMessage(_T("CreateEvent failed"));
        return;
    }

    // run listening thread

    m_hListeningThread = (HANDLE)_beginthreadex(
        NULL,
        0,
        ListenThreadProc,
        (void*) this,      
        0,
        &dwThreadID);

    if ( m_hListeningThread == NULL )
    {
        PostLogMessage(_T("_beginthreadex for listening threrad failed"));
        return;
    }

    // Show OK message
    PostLogMessage(_T("Server is running"));



      
      return TRUE;  //
When i create a new MFC project, does it need include socket support.
Since there is #include <afxsock.h> in StdAfx.h
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

Thanks, I have corrected them, but there are still some error when compile it.
Does it need any more settings? now I have put #include <winsock2.h> in both main cpp and CServerSocket.h, is this right?


--------------------Configuration: try6 - Win32 Debug--------------------
Compiling...
try6Dlg.cpp
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(68) : error C2561: 'OnInitDialog' : function must return a value
        d:\backup\desktop\power grid\pqhub\dtp\code\socket class by its\corrected\try6\try6dlg.h(38) : see declaration of 'OnInitDialog'
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(71) : error C2065: 'm_bInitialized' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(75) : error C2065: 'm_hListeningSocket' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(89) : error C2561: 'OnInitDialog' : function must return a value
        d:\backup\desktop\power grid\pqhub\dtp\code\socket class by its\corrected\try6\try6dlg.h(38) : see declaration of 'OnInitDialog'
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(93) : error C2065: 'm_hAcceptEvent' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(93) : error C2440: '=' : cannot convert from 'void *' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(96) : error C2446: '==' : no conversion from 'void *' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(96) : error C2040: '==' : 'int' differs in levels of indirection from 'void *'
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(100) : error C2561: 'OnInitDialog' : function must return a value
        d:\backup\desktop\power grid\pqhub\dtp\code\socket class by its\corrected\try6\try6dlg.h(38) : see declaration of 'OnInitDialog'
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(116) : error C2561: 'OnInitDialog' : function must return a value
        d:\backup\desktop\power grid\pqhub\dtp\code\socket class by its\corrected\try6\try6dlg.h(38) : see declaration of 'OnInitDialog'
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(122) : error C2065: 'nPort' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(135) : error C2561: 'OnInitDialog' : function must return a value
        d:\backup\desktop\power grid\pqhub\dtp\code\socket class by its\corrected\try6\try6dlg.h(38) : see declaration of 'OnInitDialog'
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(145) : error C2561: 'OnInitDialog' : function must return a value
        d:\backup\desktop\power grid\pqhub\dtp\code\socket class by its\corrected\try6\try6dlg.h(38) : see declaration of 'OnInitDialog'
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(149) : error C2065: 'm_hStopListenEvent' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(149) : error C2440: '=' : cannot convert from 'void *' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(154) : error C2561: 'OnInitDialog' : function must return a value
        d:\backup\desktop\power grid\pqhub\dtp\code\socket class by its\corrected\try6\try6dlg.h(38) : see declaration of 'OnInitDialog'
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(159) : error C2065: 'm_hListeningThread' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(159) : error C2065: '_beginthreadex' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(162) : error C2065: 'ListenThreadProc' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(165) : error C2440: '=' : cannot convert from 'void *' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(170) : error C2561: 'OnInitDialog' : function must return a value
        d:\backup\desktop\power grid\pqhub\dtp\code\socket class by its\corrected\try6\try6dlg.h(38) : see declaration of 'OnInitDialog'
Error executing cl.exe.

try6Dlg.obj - 21 error(s), 0 warning(s)
Sorry, reduced to 11 only

--------------------Configuration: try6 - Win32 Debug--------------------
Compiling...
try6Dlg.cpp
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(71) : error C2065: 'm_bInitialized' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(75) : error C2065: 'm_hListeningSocket' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(93) : error C2065: 'm_hAcceptEvent' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(93) : error C2440: '=' : cannot convert from 'void *' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(122) : error C2065: 'nPort' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(149) : error C2065: 'm_hStopListenEvent' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(149) : error C2440: '=' : cannot convert from 'void *' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(159) : error C2065: 'm_hListeningThread' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(159) : error C2065: '_beginthreadex' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(162) : error C2065: 'ListenThreadProc' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(165) : error C2440: '=' : cannot convert from 'void *' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
Error executing cl.exe.

try6Dlg.obj - 11 error(s), 0 warning(s)
now only 9 left;
--------------------Configuration: try6 - Win32 Debug--------------------
Compiling...
try6Dlg.cpp
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(8) : error C2006: #include expected a filename, found 'identifier'
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(98) : error C2065: 'm_hAcceptEvent' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(98) : error C2440: '=' : cannot convert from 'void *' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(154) : error C2065: 'm_hStopListenEvent' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(154) : error C2440: '=' : cannot convert from 'void *' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(164) : error C2065: 'm_hListeningThread' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(164) : error C2065: '_beginthreadex' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(167) : error C2065: 'ListenThreadProc' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(170) : error C2440: '=' : cannot convert from 'void *' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
Error executing cl.exe.

try6Dlg.obj - 9 error(s), 0 warning(s)
Now only 6 left;

--------------------Configuration: try6 - Win32 Debug--------------------
Compiling...
try6Dlg.cpp
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(98) : error C2065: 'm_hAcceptEvent' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(98) : error C2440: '=' : cannot convert from 'void *' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(154) : error C2065: 'm_hStopListenEvent' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(154) : error C2440: '=' : cannot convert from 'void *' to 'int'
        This conversion requires a reinterpret_cast, a C-style cast or function-style cast
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(164) : error C2065: 'm_hListeningThread' : undeclared identifier
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(167) : error C2065: 'ListenThreadProc' : undeclared identifier
Error executing cl.exe.

try6Dlg.obj - 6 error(s), 0 warning(s)
It looks like you didn't include ServerSocket.h to ServerSocket.cpp.
m_bInitialized is BOOL member which must be initialized to FALSE in constructor. Constructor must set to NULL also all socket, event and thread handles.
Why cpp file is called try6Dlg.cpp? How is this related to dialog?
The guy next to me created a dialog based MFC for me and named like that.

Now only 3 errors cannot solve, may you give any suggestion?

1)"m_hAcceptEvent = WSACreateEvent();"
'm_hAcceptEvent' : undeclared identifier
Seems should define as a handle, may I know how?

2)"    m_hStopListenEvent = CreateEvent(NULL, TRUE, FALSE, NULL)"
m_hStopListenEvent' : undeclared identifier

3)"    m_hListeningThread = (HANDLE)_beginthreadex(
        NULL,
        0,
        ListenThreadProc,
        (void*) this,      
        0,
        &dwThreadID);"
m_hListeningThread' : undeclared identifier
ListenThreadProc' : undeclared identifier



 

Hi

Last one left, any suggestion?


    m_hListeningThread = (HANDLE)_beginthreadex(
        NULL,
        0,
        ListenThreadProc,
        (void*) this,      
        0,
        &dwThreadID);

--------------------Configuration: try6 - Win32 Debug--------------------
Compiling...
try6Dlg.cpp
D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(171) : error C2065: 'ListenThreadProc' : undeclared identifier
Error executing cl.exe.

try6Dlg.obj - 1 error(s), 0 warning(s)
class CServerSocket  
{
    ...
    static unsigned ListenThreadProc(LPVOID lpVoid);
    ...
};
Yes, I have already followed it in CServerSocket.h

#include <winsock2.h>

class CServerSocket  
{
   //....


//    WSAEVENT m_hAcceptEvent;



public:

     void Initialize(int nPort);
       static unsigned ListenThreadProc(LPVOID lpVoid);   // add static keyword
     void ListenThreadFunction();
     void Cleanup();
     BOOL OnAccept(int nErrorCode);
};
Don't forget:

    SOCKET m_hListeningSocket;
    WSAEVENT m_hAcceptEvent;
    HANDLE m_hListeningThread;
    HANDLE m_hStopListenEvent;

All these members must be set to NULL in class constructor.

    BOOL m_bInitialized;

Should be set to FALSE in class constructor.

Add your own code to OnAccept function - work with clientSocket.
Client (dialog or any other class) must create CServerSocket instance and call it's Initialize function with port number. When client exits, it must call Cleanup function.


May I know how to create a constructor

And just write as m_hListeningSocket=NULL;, right?
class CServerSocket  
{
public:
    CServerSocket();

};


...

CServerSocket::CServerSocket() :
    m_bInitialized(FALSE),
    m_hListeningSocket(NULL)
    ...
{
}

or:

CServerSocket::CServerSocket()
{
    m_bInitialized = FALSE;
    m_hListeningSocket=NULL;
    ...
}
When I follow this, it generae a error point to th last line of CServerSocket.cpp, it is a blank line.
Any  suggestion?

d:\backup\desktop\power grid\pqhub\dtp\code\socket class by its\corrected\try6\cserversocket.cpp(99) : fatal error C1010: unexpected end of file while looking for precompiled header directive
#include "stdafx.h"

Add this line to the beginning of cpp file.
Now all the value has initialized as NULL.

But that line still has error.

    m_hListeningThread = (HANDLE)_beginthreadex(
        NULL,
        0,
        ListenThreadProc,
        (void*) this,      
        0,
        &dwThreadID);

Error: error C2065: 'ListenThreadProc' : undeclared identifier

The class is defined as


#include <winsock2.h>

class CServerSocket
{
      BOOL m_bInitialized;
    SOCKET m_hListeningSocket;
    WSAEVENT m_hAcceptEvent;
    HANDLE m_hListeningThread;
    HANDLE m_hStopListenEvent;

      
public:       
     //void Initialize();
      CServerSocket();
       static unsigned ListenThreadProc(LPVOID lpVoid);   // add static keyword
     void ListenThreadFunction();
     void Cleanup();
     BOOL OnAccept(int nErrorCode);
};
Now only one error

The line is
    AS.m_hListeningThread = (HANDLE)_beginthreadex(
        NULL,
        0,
        AS.ListenThreadProc,
        (void*) this,      
        0,
        &dwThreadID);

Error is;
C2664: '_beginthreadex' : cannot convert parameter 3 from 'unsigned int (void *)' to 'unsigned int (__stdcall *)(void *)'
        None of the functions with this name in scope match the target type

I defined       CServerSocket AS;
Sorry, it should be
static unsigned __stdcall ListenThreadProc(LPVOID lpVoid);

Remove AS.

class CServerSocket
{
      static unsigned __stdcall ListenThreadProc(LPVOID lpVoid);
};

...

    m_hListeningThread = (HANDLE)_beginthreadex(
        NULL,
        0,
        ListenThreadProc,
        (void*) this,      
        0,
        &dwThreadID);

If this is not compiled, post full code of h and cpp files.
still not compiled, so I put .h and .cpp into the main program, right?
Hi, I have put all into the mian program, just one more error.

static unsigned __stdcall CServerSocket::ListenThreadProc(LPVOID lpVoid)
{
    CServerSocket* p  = (CServerSocket*) lpVoid;
    p->ListenThreadFunction();

    return 0;
}

 error C2724: 'ListenThreadProc' : 'static' should not be used on member functions defined at file scope
Error executing cl.exe.
sorry CServerSocket:: has been removed
unsigned __stdcall CServerSocket::ListenThreadProc(LPVOID lpVoid)
{
    CServerSocket* p  = (CServerSocket*) lpVoid;
    p->ListenThreadFunction();

    return 0;
}

static must be in h-file:

class CServerSocket
{
      static unsigned __stdcall ListenThreadProc(LPVOID lpVoid);
};
Now I put all the .h and cpp contain into the main cpp.
What should I do?
Add your own code to OnAccept function - work with clientSocket. This code must do whatever you need talking with client - send and receive data.
Client (dialog or any other class) must create CServerSocket instance and call it's Initialize function with port number. When client exits, it must call Cleanup function.

At first stage, clientSocket must do something very fast - for example, send something to client and close immidiately. Having this working, you need to make accepted socket call asynchronous as well, exactly like listening socket.
Hi Alex,
Thanks for the patient, but now still one more error.

May I paste the code again?
Really grateful for your help.

Turbot


CServerSocket.h
//////////////////////////////////////////////////////////////////////////////////////
#include <winsock2.h>

class CServerSocket
{
public:

      BOOL m_bInitialized;
    SOCKET m_hListeningSocket;
    WSAEVENT m_hAcceptEvent;
    HANDLE m_hListeningThread;
    HANDLE m_hStopListenEvent;

      
public:       
     //void Initialize();
       CServerSocket();
       static unsigned __stdcall ListenThreadProc(LPVOID lpVoid);
     void ListenThreadFunction();
     void Cleanup();
     BOOL OnAccept(int nErrorCode);
};

/////////////////////////////////////////////////////////////////////////////////////////////////

CServerSocket.cpp
#include "stdafx.h"
#include "CServerSocket.h"

// this is static function
unsigned __stdcall CServerSocket::ListenThreadProc(LPVOID lpVoid)
{
    CServerSocket* p  = (CServerSocket*) lpVoid;
    p->ListenThreadFunction();

    return 0;
}


CServerSocket::CServerSocket()
{
      m_bInitialized=false;
      m_hListeningSocket=NULL;
    m_hAcceptEvent=NULL;
    m_hListeningThread=NULL;
    m_hStopListenEvent=NULL;

}


void CServerSocket::ListenThreadFunction()
{
    WSANETWORKEVENTS events;
    DWORD dwResult;
    int nError;
    BOOL bContinue = TRUE;

    HANDLE hEvents[2];
    hEvents[0] = m_hAcceptEvent;
    hEvents[1] = m_hStopListenEvent;

    //PostLogMessage(_T("ListenThreadFunction started"));

    while ( bContinue )
    {
        // Wait for asynchronous socket notification (see WSAEventSelect call)
        // and our own stop event

        dwResult = WSAWaitForMultipleEvents(
            2,
            hEvents,
            FALSE,
            INFINITE,
            FALSE);

        nError = WSAGetLastError();
       
        switch ( dwResult )
        {
        case WAIT_OBJECT_0:
            // m_hAcceptEvent event is signaled, new client is connected

            dwResult = WSAEnumNetworkEvents(m_hListeningSocket, m_hAcceptEvent, &events);  // get event type

            nError = WSAGetLastError();

            WSAResetEvent(m_hAcceptEvent);

            if ( dwResult == SOCKET_ERROR )
            {
//                PostLogMessage(_T("Error calling WSAEnumNetworkEvents"));
                //PrintErrorDescription(nError);
                bContinue = FALSE;
                break;
            }

            // handle signaled network events (we sobscribed to only one - FD_ACCEPT)

            if ( events.lNetworkEvents & FD_ACCEPT )
            {
                // Handle Accept network event. If function returns FALSE (failed), exit
                if ( ! OnAccept(events.iErrorCode[FD_ACCEPT_BIT]) )
                {
                    bContinue = FALSE;
                    break;
                }
            }

            break;

        case WAIT_OBJECT_0 + 1:
            // m_hStopListenEvent is signaled
            bContinue = FALSE;
            break;

        default:
//            PostLogMessage(_T("Error calling WSAWaitForMultipleEvents"));
            //PrintErrorDescription(nError);
            bContinue = FALSE;
            break;
        }

    }

//    PostLogMessage(_T("ListenThreadFunction finished"));
}

//////////////////////////////////////////////////////////////////////////
main program


#include "stdafx.h"
#include "try6.h"
#include "try6Dlg.h"
#include <winsock2.h>
#include "process.h"
#include "CServerSocket.h"


BOOL CTry6Dlg::OnInitDialog()
{
      CDialog::OnInitDialog();
      //CServerSocket AS;

      // Set the icon for this dialog.  The framework does this automatically
      //  when the application's main window is not a dialog
      SetIcon(m_hIcon, TRUE);                  // Set big icon
      SetIcon(m_hIcon, FALSE);            // Set small icon
      
      // TODO: Add extra initialization here

    unsigned int dwThreadID;

    // initialize Windows Sockets
    WSADATA wsaData;
    int nResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    int nError = WSAGetLastError();

//    if ( nResult != 0 )     // OK
//    {
        //PostLogMessage(_T("Winsock initialization failed"));
      //  PrintErrorDescription(nError);
//        return;
//    }
      
      BOOL m_bInitialized;
    SOCKET m_hListeningSocket;
    WSAEVENT m_hAcceptEvent;
    HANDLE m_hListeningThread;
    HANDLE m_hStopListenEvent;

      m_bInitialized=false;
      m_hListeningSocket=NULL;
    m_hAcceptEvent=NULL;
    m_hListeningThread=NULL;
    m_hStopListenEvent=NULL;
      
      int nPort;
      nPort=5001;
    m_bInitialized = TRUE;
    //PostLogMessage(_T("Winsock initialization succeeded"));

    // create listening socket
    m_hListeningSocket = WSASocket(
        AF_INET,
        SOCK_STREAM,
        0,
        NULL,
        0,
        WSA_FLAG_OVERLAPPED);         // non-blocking

    nError = WSAGetLastError();

//    if ( m_hListeningSocket == INVALID_SOCKET )
//    {
        //PostLogMessage(_T("Creating of listening socket failed"));
        //PrintErrorDescription(nError);
//        return;
//    }
      
    // create Accept event
    m_hAcceptEvent = WSACreateEvent();
    nError = WSAGetLastError();

//    if ( m_hAcceptEvent == WSA_INVALID_EVENT )
//    {
        //PostLogMessage(_T("Creating of Accept event failed"));
        //PrintErrorDescription(nError);
//        return;
//    }

    // Associate FD_ACCEPT socket event with m_hAcceptEvent. Now m_hAcceptEvent
    // will be signaled when new client request is received
    // by m_hListeningSocket.
    // m_hAcceptEvent is signaled when accept() may be called whith
    // expectation if immidiate success.
    nResult = WSAEventSelect(m_hListeningSocket,
                             m_hAcceptEvent,
                             FD_ACCEPT);
   
/*    if ( nResult == SOCKET_ERROR )
    {
        //PostLogMessage(_T("WSAEventSelect failed"));
        //PrintErrorDescription(nError);
        return;
    }
*/
    // fill SOCKADDR_IN structure
    SOCKADDR_IN     saServer;      

    saServer.sin_port = htons((unsigned short)nPort);
    saServer.sin_family = AF_INET;
    saServer.sin_addr.s_addr = INADDR_ANY;

    // bind SOCKADDR_IN to the listening socket
    nResult = bind(m_hListeningSocket,
                   (LPSOCKADDR)&saServer,
                   sizeof(struct sockaddr));

/*    if ( nResult == SOCKET_ERROR )
    {
        //PostLogMessage(_T("bind function failed"));
        //PrintErrorDescription(nError);
        return;
    }
*/
    // Start listening
    nResult = listen(m_hListeningSocket, SOMAXCONN);

/*    if ( nResult == SOCKET_ERROR )
    {
        //PostLogMessage(_T("listen function failed"));
        //PrintErrorDescription(nError);
        return;
    }
*/
    // create Stop Listening Thread event
    m_hStopListenEvent = CreateEvent(NULL, TRUE, FALSE, NULL);  // manually reset, initially unsignaled

/*    if ( ! m_hStopListenEvent )
    {
        //PostLogMessage(_T("CreateEvent failed"));
        return;
    }
*/
    // run listening thread

    m_hListeningThread = (HANDLE)_beginthreadex(
        NULL,
        0,
        ListenThreadProc,
        (void*) this,      
        0,
        &dwThreadID);

/*    if ( m_hListeningThread == NULL )
    {
      //  PostLogMessage(_T("_beginthreadex for listening threrad failed"));
        return;
    }
*/
    // Show OK message
    //PostLogMessage(_T("Server is running"));

      
      return TRUE;  // return TRUE  unless you set the focus to a control
}

D:\backup\desktop\power grid\pqhub\DTP\code\socket class by its\corrected\try6\try6Dlg.cpp(184) : error C2065: 'ListenThreadProc' : undeclared identifier


    m_hListeningThread = (HANDLE)_beginthreadex(
        NULL,
        0,
        ListenThreadProc,
        (void*) this,      
        0,
        &dwThreadID);
OK CTry6Dlg is client. Add line:

CServerSocket AS;

to Try6Dlg.h.

Add line:

    AS.Initialize(5001);

to OnInitDialog. Add OnDestroy function and call:

AS.Cleanup();

from it. That's all, server socket is running and listening for client connections all time dialog is active.
Sorry to bother you again, :)

I just added AS.Initialize(5001) into try6Dlg.h as below.
It seems I added in the wrong place. May you give any suggestion?


#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

AS.Initialize(5001);


/////////////////////////////////////////////////////////////////////////////
// CTry6Dlg dialog

class CTry6Dlg : public CDialog
{

public:
      CTry6Dlg(CWnd* pParent = NULL);      // standard constructor

      enum { IDD = IDD_TRY6_DIALOG };
      protected:
      virtual void DoDataExchange(CDataExchange* pDX);      // DDX/DDV support

protected:
      HICON m_hIcon;
      virtual BOOL OnInitDialog();
      afx_msg void OnPaint();
      afx_msg HCURSOR OnQueryDragIcon();

      DECLARE_MESSAGE_MAP()
};

#endif // !defined(AFX_TRY6DLG_H__6597DE31_42F4_4369_AFDF_BB1FE7964AF2__INCLUDED_)
I put AS.Initialize(5001) into the main program,

Then the compile has no error, but when build it, has 2 error.

May you help to have one more look?

Thanks

CServerSocket.cpp(106) : warning C4518: 'unsigned int ' : storage-class or type specifier(s) unexpected here; ignored
CServerSocket.cpp(106) : error C2146: syntax error : missing ';' before identifier 'dwThreadID'
CServerSocket.cpp(106) : fatal error C1004: unexpected end of file found
Generating Code...

The error line is
void CServerSocket::Initialize(int nPort)
    unsigned int dwThreadID;  ------------this line
But CServerSocket is already compiled, how can this happen?
I tried again, compile no problem now.
When build it, has some error, may you have a look?
Thanks

--------------------Configuration: try6 - Win32 Debug--------------------
Linking...
CServerSocket.obj : error LNK2001: unresolved external symbol "public: int __thiscall CServerSocket::OnAccept(int)" (?OnAccept@CServerSocket@@QAEHH@Z)
CServerSocket.obj : error LNK2001: unresolved external symbol __imp__WSAResetEvent@4
CServerSocket.obj : error LNK2001: unresolved external symbol __imp__WSAEnumNetworkEvents@12
CServerSocket.obj : error LNK2001: unresolved external symbol __imp__WSAGetLastError@0
CServerSocket.obj : error LNK2001: unresolved external symbol __imp__WSAWaitForMultipleEvents@20
CServerSocket.obj : error LNK2001: unresolved external symbol __imp__listen@8
CServerSocket.obj : error LNK2001: unresolved external symbol __imp__bind@12
CServerSocket.obj : error LNK2001: unresolved external symbol __imp__htons@4
CServerSocket.obj : error LNK2001: unresolved external symbol __imp__WSAEventSelect@12
CServerSocket.obj : error LNK2001: unresolved external symbol __imp__WSACreateEvent@0
CServerSocket.obj : error LNK2001: unresolved external symbol __imp__WSASocketA@24
CServerSocket.obj : error LNK2001: unresolved external symbol __imp__WSAStartup@8
Debug/try6.exe : fatal error LNK1120: 12 unresolved externals
Error executing link.exe.

try6.exe - 13 error(s), 0 warning(s)

Add Ws2_32.lib to the list of Linker libraries. Write implementation of CServerSocket::OnAccept function, it is missing.
You mean in CServerSocket.cpp add my own code for OnAccept(int nErrorCode); right?

Now build is ok, but when run it nothing happen.
I will try to debug it, thx for all the effort today.
May I know how many character It can received once.
Only one cheracter, or can received like 'ABC'
Conversation with client must be very short. For example, client connects, immidiately sends some message (like number of characters), server sends reply and closes client socket. In this case program generally will work. But this is not 100% correct solution. If conversation with some client hangs, the whole server hangs and doesn't talk with other clients.
You can make fast conversation (like accept, recv, send) in InAccept function and see how program works, assuming that conversation with client is very short.

Now you have listening socket written asynchronously, and synchronous OnAccept function. To make this program working 100% correctly, you need to make OnAccept asynchronous as well. The simplest way is to run worker thread for every client. In this case OnAccept returns immidiately, and thread talks with client and doesn't keep the whole server. Advanced way is using thread pool (as it is done in my project).
Actually, it do not need write, just need receive from client.

I tried samples with thread pool, but not success.

What receive by server is quite simple,
1) device ID.
2) number of data,(the real data is in DB)
Any details for Asyn accept and socket pool?
Thanks
If you get some code working, create new thread in OnAccept and pass client socket to it as parameter. In this thread you can write blocking calls (at first step) and make conversation with client. When connection with client closed, exit client thread.
Listening thread will be always responsive and ready to talk with new client. Basically, this program will be OK, after this you can think about following changes:
1) Replacing blocking calls with non-blocking in the client threads.
2) Optionally - using thread pool, you need this if server must work with many clients - let's say, hundreds.

But first make program working, it's impossible to add new featutes to program which is not work yet.
You can see details here:
http://www.codeproject.com/internet/winsockiocp.asp
My application is very very simple, the server just received a ID, togather with a number, from the client, then the server can close the socket. That's it.

I am trying it, thanks.
Hi Can this program tested by telnet? thx
How the thread being ended?
Socket server can be testes using HyperTerminal (Programs - Accessories - Communications).
CServerSocket::Cleanup function stops the listening thread.