);
}
tcpServer.Send(clientId, buf, message_size);
}
客户端完整代码如下所示,运行客户端后读者可自行使用不同的命令来接收参数返回值;
#include "AsyncTcpServer.h"
#include <string>
#include <vector>
#include <iostream>
#include <boost/tokenizer.hpp>
using namespace std;
// 存储当前客户端的ID号
std::vector<int> tcp_client_id;
// 输出特定长度的行
void PrintLine(int line)
{
for (int x = 0; x < line; x++)
{
printf("-");
}
printf("\n");
}
class CEventHandler : public CAsyncTcpServer::IEventHandler
{
public:
// 客户端连接时触发
virtual void ClientConnected(int clientId)
{
// 将登录客户端加入到容器中
tcp_client_id.push_back(clientId);
}
// 客户端退出时触发
virtual void ClientDisconnect(int clientId)
{
// 将登出的客户端从容器中移除
vector<int>::iterator item = find(tcp_client_id.begin(), tcp_client_id.end(), clientId);
if (item != tcp_client_id.cend())
tcp_client_id.erase(item);
}
// 客户端获取数据
virtual void ReceiveData(int clientId, const BYTE* data, size_t length)
{
std::cout << std::endl;
PrintLine(80);
std::cout << data << std::endl;
PrintLine(80);
std::cout << "[Shell] # ";
}
};
// 同步发送数据到指定的线程中
void send_message(CAsyncTcpServer& tcpServer, int clientId, std::string message, int message_size)
{
// 获取长度
BYTE* buf = new BYTE(message_size + 1);
memset(buf, 0, message_size + 1);
for (int i = 0; i < message_size; i++)
{
buf[i] = message.at(i);
}
tcpServer.Send(clientId, buf, message_size);
}
int main(int argc, char* argv[])
{
CAsyncTcpServer tcpServer(10, 10000);
CEventHandler eventHandler;
tcpServer.AddEventHandler(&eventHandler);
std::string command;
while (1)
{
std::cout << "[Shell] # ";
std::getline(std::cin, command);
if (command.length() == 0)
{
continue;
}
else if (command == "help")
{
printf(" _ ____ _ _ \n");
printf("| | _ _ / ___| ___ ___| | _____| |_ \n");
printf("| | | | | | \\___ \\ / _ \\ / __| |/ / _ \\ __| \n");
printf("| |__| |_| | ___) | (_) | (__| < __/ |_ \n");
printf("|_____\\__, | |____/ \\___/ \\___|_|\\_\\___|\\__| \n");
printf(" |___/ \n\n");
printf("Usage: LySocket \t PowerBy: LyShark.com \n");
printf("Optional: \n\n");
printf("\t ShowSocket 输出所有Socket容器 \n");
printf("\t GetCPU 获取CPU数据 \n");
printf("\t GetMemory 获取内存数据 \n");
printf("\t Exit 退出客户端 \n\n");
}
else
{
// 定义分词器: 定义分割符号为[逗号,空格]
boost::char_separator<char> sep(", --");
typedef boost::tokenizer<boost::char_separator<char>> CustonTokenizer;
CustonTokenizer tok(command, sep);
// 将分词结果放入vector链表
std::vector<std::string> vecSegTag;
for (CustonTokenizer::iterator beg = tok.begin(); beg != tok.end(); ++beg)
{
vecSegTag.push_back(*beg);
}
// 解析 [shell] # ShowSocket
if (vecSegTag.size() == 1 && vecSegTag[0] == "ShowSocket")
{
PrintLine(80);
printf("客户ID \t 客户IP地址 \t 客户端口 \n");
PrintLine(80);
for (int x = 0; x < tcp_client_id.size(); x++)
{
std::cout << tcp_client_id[x] << " \t "