这里所代指的字典是Python中的样子,本节内容我们将通过使用Boost中自带的Tokenizer
分词器实现对特定字符串的切割功能,使用Boost Tokenizer,可以通过构建一个分隔符或正则表达式的实例来初始化tokenizer
。然后,可以使用该实例对输入字符串进行划分。tokenizer
将在输入字符串中寻找匹配输入模式的标记,并将其拆分为单独的字符串。
首先我们先来看服务端是如何实现的,在服务端中我们接收客户端传递过来的GetProcess,lyshark.exe
字符串,然后通过使用tokenizer
分词器提取出其内部的lyshark.exe
字符串,接着调用GetProcess
函数将进程名传递进去,此时该函数会输出一个字典格式的字符串,此时通过write_some
即可将该字符串发送给客户端。
#include <iostream> #include <string> #include <boost/format.hpp> #include <boost/asio.hpp> #include <boost/array.hpp> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> using namespace std ; using namespace boost; using boost::asio::ip::tcp; std ::string GetProcess (const char *procressName) { boost::format fmt ("{'ProcName' : %s , 'Count' : 1002 }" ) ; fmt %procressName; return fmt.str(); return "{ 'ProcName' : 'None', 'Count' : 0 }" ; } int main (int argc, char * argv[]) { try { asio::io_service io_service; tcp::acceptor acceptor (io_service, tcp::endpoint(tcp::v4(), 6666 )) ; while (1 ) { tcp::socket socket (io_service) ; acceptor.accept(socket); boost::array <char , 4096 > buf; size_t len = socket.read_some(boost::asio::buffer(buf)); if (strncmp (buf.data(), "GetProcess" , strlen ("GetProcess" )) == 0 ) { std ::string strTag = buf.data(); system::error_code ignored_error; boost::char_separator<char > sep (", " ) ; typedef boost::tokenizer<boost::char_separator<char >> CustonTokenizer; CustonTokenizer tok (strTag, sep) ; std ::vector <std ::string > vecSegTag; for (CustonTokenizer::iterator beg = tok.begin(); beg != tok.end(); ++beg) vecSegTag.push_back(*beg); std ::string ref_string = GetProcess(const_cast<char *>(vecSegTag[1 ].c_str())); socket.write_some(asio::buffer(ref_string), ignored_error); } } } catch (std ::exception& e) { std ::cerr << e.what() << std ::endl ; } std ::system("pause" ); return 0 ; }
接着就是客户端部分,在该部分中我们构建GetProcess,lyshark.exe
字符串并将该字符串write_some
发送给服务端程序,接着通过read_some
等待服务端传值,当收到传递过来的字典{'ProcName' : lyshark.exe , 'Count' : 1002 }
则程序退出。
#include <iostream> #include <boost/array.hpp> #include <boost/asio.hpp> using namespace boost; using boost::asio::ip::tcp; int main (int argc, char * argv[]) { try { boost::asio::io_service io_service; tcp::endpoint end_point (boost::asio::ip::address::from_string("127.0.0.1" ), 6666 ) ; tcp::socket socket (io_service) ; socket.connect(end_point); system::error_code ignored_error; std ::string message = "GetProcess,lyshark.exe" ; socket.write_some(asio::buffer(message), ignored_error); boost::array <char , 4096 > buf = { 0 }; size_t len = socket.read_some(boost::asio::buffer(buf)); std ::cout << "返回数据: " << buf.data() << std ::endl ; } catch (std ::exception& e) { std ::cerr << e.what() << std ::endl ; } std ::system("pause" ); return 0 ; }
读者可自行编译并运行上述代码,客户端发送一个字符串,服务端处理后返回处理后的字典格式字符串,如下图所示;