echo客戶端的工作原理也很簡單:
1、向服務器端發(fā)送一個字符串;
2、接收服務器的返回信息(如果是echo服務器就會返回發(fā)送出去的字符串本身)。
3、在標準輸出中回顯服務器返回的信息。
與ehco服務器類似,我們的echo客戶端類也可以從TCPClientSock中派生出來:
//Filename AppSock.hpp
#ifndef APP_SOCK_HPP
#define APP_SOCK_HPP
#include <string>
#include "SockClass.hpp"
class TCPEchoClient: public TCPClientSock{
public:
TCPEchoClient(
const char* server_IP,
unsigned short server_port,
int pre_buffer_size = 32);
~TCPEchoClient();
bool doEcho(const std::string& echo_message) const;
};
#endif //AppSock.hpp
我們的doEcho()接收一個C++風格的字符串(std::string),將返回值設計成bool是出于以下考慮:我們希望與服務器斷開連接的信息能反饋到主程序中,并且在斷開連接后終止echo客戶端的程序。所以,返回true表示仍然與服務器保持連接,否則則已經(jīng)斷開(或者異常)。
#include "AppSock.hpp"
TCPEchoClient::TCPEchoClient(
const char* server_IP,
unsigned short server_port,
int pre_buffer_size):
TCPClientSock(server_IP, server_port, pre_buffer_size)
{}
TCPEchoClient::~TCPEchoClient()
{}
bool TCPEchoClient::doEcho(const std::string& echo_message) const
{
if (TCPSend(echo_message.data(), echo_message.size()) < 0) {
return false;
}
size_t total_received_length = 0;
while (total_received_length < echo_message.size()) {
if (TCPReceive() <= 0) {
return false;
}
std::cout.write(preBuffer, preReceivedLength);
total_received_length += preReceivedLength;
}
std::cout << std::endl;
return true;
}
因為我們是先發(fā)再收,我們接收前是知道應該收到多少字節(jié)的信息的。由于TCP協(xié)議對邊緣的無保障,我們應該假定是是最不利的情況,也就是一次recv()不能接收完我們需要的數(shù)據(jù),所以,如果接收到的字節(jié)數(shù)小于我們的預期,就再次接收,直到跟我們發(fā)送的字符串長度一樣。雖然事實上在這種小數(shù)據(jù)的傳輸中很難遇到以上所描述的那種情況,但是在網(wǎng)絡程序的設計中,應該堅持這樣一個基本假設:你永遠不知道遠程的主機會出什么狀況,所以永遠以最壞的可能性來設計程序。
最后是主程序。主程序在標準輸入中阻塞等待用于echo的信息,為了避免無限循環(huán),我們也設計一個可以關閉服務器端的命令/exit。這樣,輸入/exit或者服務器斷開都可以導致客戶端終止。
#include "SockClass.hpp"
#include "AppSock.hpp"
int main(int argc, char* argv[])
{
unsigned short server_port = 5000;
if (argc == 3 && atoi(argv[2]) > 0) {
server_port = atoi(argv[2]);
}
WinsockAPI winsockInfo;
winsockInfo.showVersion();
TCPEchoClient echo_client(argv[1], server_port);
std::string msg;
bool go_on = true;
while (msg != "/exit" && go_on == true) {
std::cout << "Echo: ";
std::getline(std::cin, msg);
go_on = echo_client.doEcho(msg);
}
return 0;
}
本節(jié)源代碼下載:
linux:
http://www.163pan.com/files/c0x000g0x.htmlwin32:
http://www.163pan.com/files/c0x000g0y.html
posted on 2010-06-08 11:49
lf426 閱讀(2276)
評論(1) 編輯 收藏 引用 所屬分類:
SDL入門教程 、
socket 編程入門教程