views:

61

answers:

3

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");
A: 

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.

Pavel Radzivilovsky
i know i just wanted to see if i get an incoming connection and it seems like i don't
fanq
the server is another application residing on localhost (it's not the same MFC application)
fanq
Do you mean that OnAccept() is not called?
Pavel Radzivilovsky
yes, its not called
fanq
+1  A: 

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.

valdo
A: 

Yes, I agree with above two.

Meteor