fanq
fanq

Reputation: 3

Working with sockets in MFC

I'm trying to make a MFC application(client) that connects to a server on ("localhost",port 1234), the server replies to the client and the client reads from the server's response.

The server is able to receive the data from the client and it sends the reply back to the socket from where it received it, but I am unable to read the reply from within the client.

I am making a CAsyncSocket to connect to the server and send data and a CAsyncSocket with overloaded methods onAccet and onReceive to read the reply from the server. Please tell me what I'm doing wrong.

    class ServerSocket:public CAsyncSocket{
    public:
    void OnAccept(int nErrorCode){
        outputBox->SetWindowTextA("RECEIVED DATA");
        CAsyncSocket::OnAccept(nErrorCode);
    }
};

//in ApplicationDlg I have:

socket.Create();
socket.Connect("127.0.0.1",1234);
socket.Send(temp,strlen(temp));    //this should be sending the initial message

if(!serverSocket.Create())  //this should get the response i guess...
    AfxMessageBox("Could not create server socket");

if(!serverSocket.Listen())
    AfxMessageBox("Could not listen to socket");

Upvotes: 0

Views: 4645

Answers (2)

valdo
valdo

Reputation: 12943

You should be aware that all network operations are potentially time-consuming operations. Now, since you're using MFC's CAsyncSocket class, it performs all the operations asynchronously (doesn't block you). But return from the function doesn't mean it's already completed.

Let's look at the following lines of code:

socket.Connect("127.0.0.1",1234);
socket.Send(temp,strlen(temp));    //this should be sending the initial message

The first is the call to Connect, which most probably doesn't complete immediately. Next, you call Send, but your socket isn't connected yet! It definitely returns you an error code, but since you don't bother checking its return value - you just happily wait to receive something.

So, the next rule for you, my friend, should be checking every return value for every function that you call, especially when it comes to networking where errors are legitimate and happen frequently.

You should only start sending after OnConnect has been called.

Upvotes: 2

Pavel Radzivilovsky
Pavel Radzivilovsky

Reputation: 19104

First, I don't see where you send the data to client (on server).

Second, Accept() does not mean data received. Accept means you have a new incoming connection, for which you need to create Another socket, to which data should be sent.

Upvotes: 0

Related Questions