Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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;
}
like image 305
Kakashi Avatar asked Dec 19 '25 13:12

Kakashi


2 Answers

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..

like image 177
Germann Arlington Avatar answered Dec 22 '25 03:12

Germann Arlington


Bind the server socket first

serverSocket.Bind(3333)

and then listen.

like image 38
Unknown Avatar answered Dec 22 '25 03:12

Unknown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!