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?
Aucun commentaire:
Enregistrer un commentaire