Hi all,

My csocket program is as follow. The program run properly but the server don't wait the message from client and the client also don't send. Can anyone help me what's the problem in client server communciation API. Thanks a lot in advance.

#include <afxwin.h>         // MFC core and standard components
#include <afxext.h>         // MFC extensions
#include <afxsock.h>     // MFC socket extensions

#include <winsock.h>
//#include <windows.h>

//CSocket gensoc;

void server( int port)
{
    printf("\n Server \n\n");

    CSocket gensoc;
    gensoc.Create ( port );

    SOCKADDR_IN addr;

    memset( &addr, 0, sizeof( SOCKADDR_IN ) );
    addr.sin_family = AF_INET;
    addr.sin_port = htons (port);

    addr.sin_addr.s_addr = INADDR_ANY;


    if (bind( gensoc, (SOCKADDR *)&addr , sizeof(addr)))
    {
        printf ("\n Bind success");
    }
    else
    {
        printf ("\n Bind fail");
    }

    //gensoc.Listen();


    if (listen( gensoc,0) )
    {
        printf ("\n listening" );

    }
    else
    {
        printf ("\n socket error" );
    }


    CSocket newsoc;
    int nlen = sizeof(addr);

    //gensoc.Accept(newsoc);

    if( accept (gensoc,(SOCKADDR *)&addr , &nlen))

    {
        printf ("\n Accept() function success" );

    }
    else
    {
        printf ("\n Accept() function failed" );
    }

    int nBytesRead;
    char cbBuffer[2000];

    nBytesRead = gensoc.Receive ( cbBuffer, sizeof ( cbBuffer ));
gensoc.close();
newsoc.close();

}

void client( char* remote_mac, int port)
{
    printf("\n Client \n\n");

    CSocket gensoc;
    gensoc.Create ( port );

    SOCKADDR_IN addr;

    memset( &addr, 0, sizeof( SOCKADDR_IN ) );
    addr.sin_family = AF_INET;
    addr.sin_port = htons (port);

    addr.sin_addr.s_addr = INADDR_ANY;


    /****************************************/

    addr.sin_addr.s_addr = inet_addr( remote_mac );

    /*
    if (addr.sin_addr.s_addr == INADDR_NONE)
    {
        HOSTENT *lpHostEnt;
        lpHostEnt = gethostbyname( remote_mac );
        if (!lpHostEnt)
        {
            char* lpAddr = ( char* ) inet_ntoa(*(LPIN_ADDR)*(lpHostEnt ->h_addr_list) );
            addr.sin_addr.s_addr = **(int**)(lpHostEnt->h_addr_list);
        }
    }*/

//if (gensoc.Connect( (SOCKADDR*) &addr, sizeof( SOCKADDR_IN ) ) )
    if (connect(gensoc, (SOCKADDR*) &addr, sizeof( SOCKADDR_IN ) ) )
    {
        printf( "\n connect was successful" );
    }
    else
    {
        printf( "\nconnect was not successful" );
    }


    int nBytesWritten;
    static char msg[] = "Hello socket";

    nBytesWritten = gensoc.Send ( msg, sizeof ( msg ));
gensoc.close();

}

void main( int argc, char* argv[] )
{

    switch( argc )
    {
        case 2:
            server( atoi( argv[1] ) );
            break;
        case 3:
            client( argv[1], atoi( argv[2]) );
            break;
        default:
            printf("Usage: main[RemoteMachien] port#\n");
            printf("If remote machine is not provided, application will run in server mode listening to specified port number \n");
            printf("If remote machine is provided, application will run in client trying to reach specified server \n");
    }



}

Dani AI

Generated

Short diagnosis: the code is mixing MFC's CSocket wrapper with raw Winsock calls, it checks return values backwards, and it performs the read on the listening socket instead of on the accepted socket. As pointed out, Winsock functions must be initialized (WSAStartup) — for MFC you should call AfxSocketInit() — and bind/listen/connect return 0 on success (not nonzero). Those three issues will make the server never properly accept or the client never properly send.

Fixes to apply (pick one API and stick to it)

  • If you use MFC CSocket: call AfxSocketInit() at startup, use CSocket::Create(port), CSocket::Listen(backlog>0), then CSocket::Accept(newSock). Do data I/O on the accepted socket (newSock.Receive / newSock.Send). Check BOOL returns and catch CSocketException for diagnostics.
  • If you use raw Winsock: call WSAStartup, create a SOCKET with socket(), then bind/listen/accept/connect on that SOCKET and use WSAGetLastError() to diagnose failures.

Minimal MFC pattern (illustrative)

if (!AfxSocketInit()) return;
CSocket listenSock;
if (!listenSock.Create(port)) { /* handle error */ }
if (!listenSock.Listen(5)) { /* handle error */ }
CSocket clientSock;
if (!listenSock.Accept(clientSock)) { /* handle error */ }
char buf[2048] = {0};
int n = clientSock.Receive(buf, sizeof(buf)-1);

Practical debugging tips

  • Replace any raw calls like bind(listenObject,...) or accept(listenObject,...) with the CSocket methods above.
  • Use a nonzero backlog (5 or SOMAXCONN).
  • Print error codes (WSAGetLastError or details from CSocketException) when a call fails.
  • Test the server with telnet/netcat from the client machine to isolate whether Connect/Accept or Send/Receive is failing.

Follow those clean separations and the server will block at Accept and the client will Connect/Send as expected.

Recommended Answers

All 2 Replies

Use this before using the Winsock Functions

WSADATA wsaData;
	int Ret;
    if ((Ret = WSAStartup(MAKEWORD(2,2), &wsaData)) != 0)
   {
      printf("WSAStartup failed with error %d\n", Ret);
      return;
   }

Some other things that I saw later..
listen and bind and maybe the other functions also, return 0 on correct operation. So the code

if ( bind( parameters...) )
{
      //COrrect op
}
else
{
        // wrong
}

is wrong.
It should be

if ( bind( parameters ) == 0 )
{
       //Correct Operation
}
else
{
       //Error
}

Refer the Specifications of the bind, listen, connect, etc. functions and correct the code accordingly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.