http会话是服务器用于在用户与服务器交互期间跟踪用户状态的机制。由于http协议本身是无状态的(每次请求都是独立的),因此服务器需要通过会话来记住用户的信息。
当用户首次访问网站时,服务器会为用户创建一个唯一的会话ID,并通过Cookie将其发送到客户端。
客户端在随后的请求中会携带这个会话ID,服务器通过会话ID来识别用户,从而获取用户的会话信息。
服务器通常会将会话信息存储在内存、数据库或缓存中。
与Cookie类似,由于会话ID是在客户端和服务器之间传递的,因此也存在被窃取的风险。
尽管Cookie被盗取了,用户仅泄露了一个会话ID,暂时没有泄露私密信息的风险。
会话ID有助于服务器端管理客户端的有效性,例如异地登录。
可以通过HTTPS和设置适当的Cookie属性(如HttpOnly和Secure)来增强安全性。
会话可以设置超时时间,超过这个时间后,会话会自动失效。
服务器也可以主动使会话失效,例如当用户登出时。
部分核心代码:
Session.hpp
#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <ctime>
#include <unistd.h>
#include <unordered_map>
<p>// 用来进行测试说明
class Session {
public:
Session(const std::string& username, const std::string& status)
: _username(username), _status(status) {
_create_time = time(nullptr); // 获取时间戳就行了,后面实际需要,就转化就转换一下
}
~Session() {}</p><p>public:
std::string _username;
std::string _status;
uint64_t _create_time;
// 当然还可以再加任何其他信息,看你的需求
};</p><p>using session_ptr = std::shared_ptr<Session>;</p><p>class SessionManager {
public:
SessionManager() {
srand(time(nullptr) ^ getpid());
}</p><pre class="brush:php;toolbar:false;"><code>std::string AddSession(session_ptr s) {
uint32_t randomid = rand() + time(nullptr); // 随机数+时间戳,实际有形成 sessionid 的库,比如 boost uuid 库,或者其他第三方库等
std::string sessionid = std::to_string(randomid);
_sessions.insert(std::make_pair(sessionid, s));
return sessionid;
}
session_ptr GetSession(const std::string sessionid) {
if (_sessions.find(sessionid) == _sessions.end()) return nullptr;
return _sessions[sessionid];
}
~SessionManager() {}private: std::unordered_map<std::string, session_ptr> _sessions; };
HttpProtocol.hpp
#pragma once</p><h1>include <iostream></h1><h1>include <string></h1><h1>include <sstream></h1><h1>include <vector></h1><h1>include <memory></h1><h1>include <ctime></h1><h1>include <functional></h1><h1>include "TcpServer.hpp"</h1><h1>include "Session.hpp" // 引入 session</h1><p>const std::string HttpSep = "\r\n";</p><p>// 可以配置的
const std::string homepage = "index.html";
const std::string wwwroot = "./wwwroot";</p><p>class HttpRequest {
public:
HttpRequest() : _req_blank(HttpSep), _path(wwwroot) {}</p><pre class="brush:php;toolbar:false;"><code>bool GetLine(std::string& str, std::string* line) {
auto pos = str.find(HttpSep);
if (pos == std::string::npos) return false;
*line = str.substr(0, pos); // \r\n
str.erase(0, pos + HttpSep.size());
return true;
}
void Parse() {
// 解析出来 url
std::stringstream ss(_req_line);
ss >> _method >> _url >> _http_version;
// 查找 cookies
std::string prefix = "Cookie: ";
for (auto& line : _req_header) {
std::string cookie;
if (strncmp(line.c_str(), prefix.c_str(), prefix.size()) == 0) // 找到了
{
cookie = line.substr(prefix.size()); // 截取"Cookie: "之后的就行了
_cookies.emplace_back(cookie);
break;
}
}
// 查找 sessionid
prefix = "sessionid=";
for (const auto& cookie : _cookies) {
if (strncmp(cookie.c_str(), prefix.c_str(), prefix.size()) == 0) {
_sessionid = cookie.substr(prefix.size()); // 截取"sessionid="之后的就行了
break;
}
}
}
// 其他成员变量和方法...
std::string _req_line;
std::vector<std::string> _req_header;
std::string _req_blank;
std::string _req_content;
// 解析之后的内容
std::string _method;
std::string _url; // / /dira/dirb/x.html / dira / dirb / XX ? usrname = 100 && password = 1234 / dira / dirb
std::string _http_version;
std::string _path; // "./wwwroot"
std::string _suffix; // 请求资源的后缀
std::vector<std::string> _cookies; // 其实 cookie 可以有多个,因为 Set - Cookie 可以被写多条,测试,一条够了。
std::string _sessionid; // 请求携带的 sessionid,仅仅用来测试};
const std::string BlankSep = " "; const std::string LineSep = "\r\n";
class HttpResponse { public: HttpResponse() : _http_version("HTTP/1.0"), _status_code(200), _status_code_desc("OK"), _resp_blank(LineSep) {}
<code>void SetCode(int code) {
_status_code = code;
}
void SetDesc(const std::string& desc) {
_status_code_desc = desc;
}
void MakeStatusLine() {
_status_line = _http_version + BlankSep +
std::to_string(_status_code) + BlankSep + _status_code_desc +
LineSep;
}
void AddHeader(const std::string& header) {
_resp_header.push_back(header + LineSep);
}
void AddContent(const std::string& content) {
_resp_content = content;
}
std::string Serialize() {
MakeStatusLine();
std::string response_str = _status_line;
for (auto& header : _resp_header) {
response_str += header;
}
response_str += _resp_blank;
response_str += _resp_content;
return response_str;
}
~HttpResponse() {}</code>private: std::string _status_line; std::vector<std::string> _resp_header; std::string _resp_blank; std::string _resp_content; // body
<code>// httpversion StatusCode StatusCodeDesc std::string _http_version; int _status_code; std::string _status_code_desc;</code>
};
class Http { private: std::string GetMonthName(int month) { std::vector<std::string> months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; return months[month]; }
<code>std::string GetWeekDayName(int day) {
std::vector<std::string> weekdays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
return weekdays[day];
}
std::string ExpireTimeUseRfc1123(int t) // 秒级别的未来 UTC 时间
{
time_t timeout = time(nullptr) + t;
struct tm* tm = gmtime(&timeout); // 这里不能用 localtime,因为 localtime 是默认带了时区的.gmtime 获取的就是 UTC 统一时间
char timebuffer[1024];
// 时间格式如: expires=Thu, 18 Dec 2024 12:00:00 UTC
snprintf(timebuffer, sizeof(timebuffer), "%s, %02d %s %d %02d:%02d:%02d UTC",
GetWeekDayName(tm->tm_wday).c_str(),
tm->tm_mday,
GetMonthName(tm->tm_mon).c_str(),
tm->tm_year + 1900,
tm->tm_hour,
tm->tm_min,
tm->tm_sec);
return timebuffer;
}</code>public: Http(uint16_t port) { _tsvr = std::make_unique<TcpServer>(port, std::bind(&Http::HandlerHttp, this, std::placeholders::_1)); _tsvr->Init(); _session_manager = std::make_unique<SessionManager>(); }
<code>std::string ProveCookieWrite() // 证明 cookie 能被写入浏览器
{
return "Set-Cookie: username=zhangsan;";
}
std::string ProveCookieTimeOut() {
return "Set-Cookie: username=zhangsan; expires=" + ExpireTimeUseRfc1123(60) + ";"; // 让 cookie 1min 后过期
}
std::string ProvePath() {
return "Set-Cookie: username=zhangsan; path=/a/b;";
}
std::string ProveSession(const std::string& session_id) {
return "Set-Cookie: sessionid=" + session_id + ";";
}
std::string HandlerHttp(std::string request) {
HttpRequest req;
HttpResponse resp;
req.Deserialize(request);
req.Parse();
// req.DebugHttp();
// std::cout << "用户" << user << "已登录" << std::endl;
std::string sessionid = _session_manager->AddSession(s);
lg.LogMessage(Debug, "%s 被添加, sessionid是: %s\n", user.c_str(), sessionid.c_str());
resp.AddHeader(ProveSession(sessionid));
} else {
// 当浏览器在本站点任何路径中活跃,都会自动提交 sessionid, 我们就能知道谁活跃了.
std::string sessionid = req.SessionId();
if (!sessionid.empty()) {
session_ptr s = _session_manager->GetSession(sessionid);
// 这个地方有坑,一定要判断服务器端 session 对象是否存在,因为可能测试的时候
// 浏览器还有历史 sessionid,但是服务器重启之后,session 对象没有了.
if (s != nullptr)
lg.LogMessage(Debug, "%s 正在活跃.\n", s->_username.c_str());
else
lg.LogMessage(Debug, "cookie : %s 已经过期, 需要清理\n", sessionid.c_str());
}
}
resp.SetCode(200);
resp.SetDesc("OK");
resp.AddHeader("Content-Type: text/html");
// resp.AddHeader(ProveCookieWrite()); //测试 cookie 被写入与自动提交
// resp.AddHeader(ProveCookieTimeOut()); //测试过期时间的写入
// resp.AddHeader(ProvePath()); // 测试路径
resp.AddContent("<h1>helloworld</h1>");
return resp.Serialize();</code>}
void Run() { _tsvr->Start(); }
~Http() {}
private: std::unique_ptr<TcpServer> _tsvr; std::unique_ptr<SessionManager> _session_manager; };
准备两个浏览器:Google Chrome 和 Microsoft Edge(Windows自带的)
删除浏览器中指定服务器上的所有Cookie
如果之前没有进行过测试,就不需要删除。Chrome的Cookie有些特殊,可能无法通过实验测试,尝试打印Chrome浏览器发送的HTTP请求,观察Cookie部分,你就能明白为什么需要删除历史Cookie。
Microsoft Edge

Google Chrome

访问/login, 模拟登录
Microsoft Edge

Google Chrome

两个浏览器访问任意的站点资源

服务器端已经能够识别是哪个浏览器了。
总结:
HTTP Cookie和会话都是用于在Web应用中跟踪用户状态的机制。Cookie存储在客户端,而会话存储在服务器端。它们各有优缺点,通常在实际应用中会结合使用,以达到最佳的用户体验和安全性。
感谢各位大佬的支持!!!
互三啦!!!
以上就是【在Linux世界中追寻伟大的One Piece】HTTP Session的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号