gpt4 book ai didi

c++ - boost::asio 每个客户端的单独数组

转载 作者:太空宇宙 更新时间:2023-11-04 14:20:22 24 4
gpt4 key购买 nike

我学过 C++,现在我想继续学习一些网络编程。我决定使用 boost::asio 因为它是多平台的。我写了这个简单的程序:

客户:

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

enum { max_length = 1000000 };

int main(int argc, char* argv[])
{
while(1)
{

try
{
if (argc != 3)
{
std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n";
return 1;
}

boost::asio::io_service io_service;

tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), argv[1], argv[2]);
tcp::resolver::iterator iterator = resolver.resolve(query);

tcp::socket s(io_service);
s.connect(*iterator);

using namespace std; // For strlen.

std::cout << "Enter message: ";
char request[max_length];
std::cin.getline(request, max_length);
if (request == "\n")
continue;

size_t request_length = strlen(request);
boost::asio::write(s, boost::asio::buffer(request, request_length));

char reply[max_length];
boost::system::error_code error;
size_t reply_length = s.read_some(boost::asio::buffer(reply), error);

if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.




std::cout << "Reply is: ";
std::cout.write(reply, reply_length);

std::cout << "\n";
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
exit(1);
}
}

return 0;
}

服务器:

#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <string>

using boost::asio::ip::tcp;
const int max_length = 1000000;

std::string user_array[100];

typedef boost::shared_ptr<tcp::socket> socket_ptr;

unsigned short analyze_user_request(std::string& user_request, short unsigned* ID, std::string* request_value)
{
// function returns:
// 0: if user request is incorrect
// 1: if user requests "PUT" operation
// 2: if user requests "GET" operation
// Furthermore, if request is correct, its value (i.e. ID number and/or string) is saved to short unsigned and string values passed by pointers.

boost::regex exp("^[[:space:]]*(PUT|GET)[[:space:]]+([[:digit:]]{1,2})(?:[[:space:]]+(.*))?$");

boost::smatch what;
if (regex_match(user_request, what, exp, boost::match_extra))
{
short unsigned id_number = boost::lexical_cast<short unsigned>(what[2]);

if (what[1] == "PUT")
{
boost::regex exp1("^[a-zA-Z0-9]+$");
std::string value = boost::lexical_cast<std::string>(what[3]);
if (value.length() > 4095)
return 0;
if (!regex_match(value, exp1))
return 0;
else
{
*request_value = value;
*ID = id_number;
return 1;
}
}

if (what[1] == "GET")
{
*ID = id_number;
return 2;
}

}

if (!regex_match(user_request, what, exp, boost::match_extra))
return 0;
}


void session(socket_ptr sock)
{
try
{
for (;;)
{
char data[max_length];

boost::system::error_code error;
size_t length = sock->read_some(boost::asio::buffer(data), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
// convert buffer data to string for further procession
std::string line(boost::asio::buffers_begin(boost::asio::buffer(data)), boost::asio::buffers_begin(boost::asio::buffer(data)) + length);
std::string reply; // will be "QK", "INVALID", or "OK <value>"
unsigned short vID;

unsigned short* ID = &vID;
std::string vrequest_value;
std::string* request_value = &vrequest_value;

unsigned short output = analyze_user_request(line, ID, request_value);

if (output == 1)
{
// PUT
reply = "OK";
user_array[*ID] = *request_value;
}

else if (output == 2)
{
// GET
reply = user_array[*ID];
if (reply == "")
reply = "EMPTY";

}

else
reply = "INVALID";

boost::system::error_code ignored_error;
size_t ans_len=reply.length();
boost::asio::write(*sock, boost::asio::buffer(reply));
}
}
catch (std::exception& e)
{
std::cerr << "Exception in thread: " << e.what() << "\n";
}
}

void server(boost::asio::io_service& io_service, short port)
{
tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
for (;;)
{
socket_ptr sock(new tcp::socket(io_service));
a.accept(*sock);
boost::thread t(boost::bind(session, sock));
}
}

int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: blocking_tcp_echo_server <port>\n";
return 1;
}

boost::asio::io_service io_service;

using namespace std; // For atoi.
server(io_service, atoi(argv[1]));
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}

return 0;
}

基本上,它是一个允许用户在服务器上存储数据的应用程序。用户可以使用 PUT 命令后跟 ID 号和数据值插入新数据,并使用 GET 命令后跟 ID 检索数据。用户请求在 analyze_user_request 函数中处理,随后写入或读取数组。问题是现在所有客户端都在使用相同的全局数组。这意味着如果一个客户端在特定 ID 下保存了一些东西,所有其他客户端都可以读取它,因为它们访问同一个数组。我想知道,如何将数组与不同的客户端相关联,并在新客户端连接时创建一个新数组?

最佳答案

如何将 session 数据封装到一个类中,并为每个连接创建单独的 session 对象。大概是这样的:

session 类定义:

class Session {
public:
// logic from your session function
void handleRequests(socket_ptr sock);

private:
// session data here
}

typedef boost::shared_ptr<Session> SessionPtr;

在接受循环的“服务器”函数中创建新对象并将其传递给新线程:

SessionPtr newSession(new Session());

boost::thread acceptThread(boost::bind(&Session::handleRequests, newSession, sock));

对于代码中可能存在的错误,我深表歉意,我离我的开发环境很远,无法对其进行测试。

有关单独处理多个连接的更优雅的解决方案,请参阅 boost::asio 示例“聊天服务器”:http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/example/chat/chat_server.cpp

关于c++ - boost::asio 每个客户端的单独数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8102867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com