[ LiB ] |
Now that you've got a more flexible server running, you'll probably want a more flexible client as well. Luckily, only a few more changes are needed to enable the client to send any message you want. I've also decided to add the ability to send more than one message before quitting.
The demo can be found in the directory /Demos/Chapter02/Demo04-HelloInternetClientV2/, in the file Demo04.cpp. As with all the other demos in this chapter, it is a console app, and can be compiled using the instructions from Appendix A (on the CD).
The demo starts off with Code Blocks 2.1 and 2.2 and also uses Code Block 2.4 (from Demo 2.2, shown previously). So at this point in time, you have a connected data socket called sock , and you're ready to start sending data!
This first section of code starts a loop that loops until the user tells it to stop, and gets user input from the console, separated by line:
bool done = false; cout << "Type data to send now:" << endl; while( !done ) { // get data to send cin.getline( message, 128 );
The getline() function of cin basically tells it to get data and store it into the message buffer until the user presses Enter, or 128 characters are reached. Once you've done that, you can send the data:
// send data err = send( sock, message, strlen( message ) + 1, 0 ); if( err == -1 ) { cout << "Socket sending error!" << endl; return 0; } if( strcmp( message, "servquit" ) == 0 strcmp( message, "quit" ) == 0 ) { done = true; } } shutdown( sock, 2 ); CloseSocket( sock ); CloseSocketLib; }
If the message is equal to servquit or quit , the demo quits and closes its sockets. That's pretty much it.
You can now run the program in conjunction with Demo 2.3. Figure 2.11 shows the programs in action.
Essentially, what you've created is a one-way chat server; people can send messages to the server, but the server doesn't send anything back! It's not too useful, but it's still cool.
[ LiB ] |