Reputation: 20987
Through a tutorial I was able to built a C++ client application that connects to a server and is able to send and receive data.
Currently the application ends after it receives a string from the server. What I want to do is to let the client keep listening for incoming data.
Currently a part of my code looks like this:
string tcp_client::receive(int size=512)
{
char buffer[size];
string reply;
//Receive a reply from the server
if( recv(sock , buffer , sizeof(buffer) , 0) < 0)
{
puts("recv failed");
}
reply = buffer;
return reply;
}
int main(int argc , char *argv[])
{
tcp_client c;
string host;
cout<<"Enter hostname : ";
cin>>host;
c.conn(host , 4004);
//send some data
c.send_data("TEST STRING \n\r\n");
//receive and echo reply
// (want to keep listening here for data)
cout<<c.receive(1024);
//done
return 0;
}
I don't want the client to end but I want it to keep listening for data. I'm thinking about adding this code:
while(buffer = c.receive(1024))
{
// do something with buffer ... switch/case construction
// After that, start listening again
}
First of all I'm not sure if this works. But second, I'm also not sure if it's smart to put in a never ending while loop in there (never ending, until I terminate the application of course).
Can I simply put in a while loop like that? Or are there other. better methods to make a client application keep listening for data?
Upvotes: 0
Views: 7090
Reputation: 741
Yes you should put receive in a loop. But you should know that the receive call will block your program until it finds any data. That means if you are working with a GUI, your GUI will halt until the receive will unblock the program. For console application its ok..
Upvotes: 0
Reputation: 7447
You should check if you at a certain point you receive 0 bytes , which means that the other end has closed the connection and is not going to send anymore. That means that you can close your socket too and close the application.
Under normal condition , when the server is also running, receive is a blocking call, it just hangs there until there is something received.
Now if the server closes the connection you really must exit the endless loop or you will continuously call receive on a socket that is closed which will return immediately taking a lot of load on your cpu.
All programs should generally take care of the error conditions or unexpected behavior can occur.
Upvotes: 1