Kakashi
Kakashi

Reputation: 31

"MFC/C++ Socket programming.." How to connect server and client?

I used a code for MFC/C++ socket programming but it's only working when I make the server and client on the same PC , but when I use the client on different PC ,it fails to find the server and the connection is failed . I don't know if the problem with the local IP of the server I use or with the code any help please :) !

the following code is server side :-

#include <afx.h>
#include <afxext.h>
#include <afxsock.h>
#include <iostream>

using namespace std;

int main() 
{
    AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);
    AfxSocketInit();
    CSocket serverSocket;
    serverSocket.Create(3333);
    serverSocket.Listen();
    CSocket clientSocket;

    while(serverSocket.Accept(clientSocket))
    {
        CString s;

        while(s!="bye")
        {
            char msg[128];

            if(clientSocket.Receive(msg, 128)<0)break;

            s = msg;
            cout<<"Client: "<<msg<<endl;
            sprintf_s(msg, 128, "Your msg (%d letter) arrived successfully.",
            strlen(msg));
            clientSocket.Send(msg, 128);

            if(s=="shutdown")exit(0);
        }

        clientSocket.Close();
    }

    return 0;
}

the following code for client side :-

 #include <afx.h>
 #include <afxext.h>
 #include <afxsock.h>
 #include <iostream>

 using namespace std;

int main()
{
    AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0);
    AfxSocketInit();
    CSocket clientSocket;
    clientSocket.Create();

    if(clientSocket.Connect("192.168.1.2", 3333))
    {
        cout<<"Connected to server."<<endl;
        CString s;

        while(s!="bye" && s!="shutdown")
        {
            char msg[128];
            cin.getline(msg, 128);
            s = msg;
            clientSocket.Send(msg, 128);

            if(clientSocket.Receive(msg, 128)<0)break;

            cout<<msg<<endl;
        }
    }
    else
    {
       cout<<"Cannot find server."<<endl;
    }

    return 0;
}

Upvotes: 3

Views: 9696

Answers (2)

Unknown
Unknown

Reputation: 11

Bind the server socket first

serverSocket.Bind(3333)

and then listen.

Upvotes: 1

Germann Arlington
Germann Arlington

Reputation: 3353

How about attempting to connect to another server address in your client instead of your currently fixed address?

if(clientSocket.Connect("192.168.1.2", 3333))

P.S. It is always best to set parameters in your programs for such things as addresses and port numbers..

Upvotes: 1

Related Questions