程序按ctrl+c意味着系统产生了中断信号kill -s INT然后发给程序
在C++中signal的使用方法:
头文件包含signal.h 但asio.hpp已经包含了也可以省略
可以直接挂在ASIO使用或定义在全局处理
函数定义代码部分:
static std::function<void()> safeQuit;
void signalHandler(int sig) {
BOOST_LOG_TRIVIAL(info) << "handle system signal "<<sig;
if (safeQuit) {
safeQuit();
safeQuit = nullptr;
}
}
safeQuit=nullptr:保证只执行一次
一般应用程序这样写足够了,实际在复杂的项目中可能会有问题
在main函数里定义好safeQuit函数
safeQuit = [&io_service]{
io_service.stop();};
通过main函数下加入signal(SIGINT,signalHandler)调用
sigint在windows和linux是通用的都可以这么写
asio聊天室系统加入signal完整服务器代码部分:
#include "chat_message.h"
#include "JsonObject.h"
#include "Protocal.pb.h"
#include <boost/asio.hpp>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <chrono>
#include <deque>
#include <iostream>
#include <list>
#include <memory>
#include <set>
#include <thread>
#include <utility>
#include <mutex>
#include <cstdlib>
using boost::asio::ip::tcp;
//----------------------------------------------------------------------
using chat_message_queue = std::deque<chat_message>;
using chat_message_queue2 = std::list<chat_message>;
//----------------------------------------------------------------------
// stread_clock
std::chrono::system_clock::time_point base;
//----------------------------------------------------------------------
class chat_session;
using chat_session_ptr = std::shared_ptr<chat_session>;
class chat_room {
public:
chat_room(boost::asio::io_service& io_service) : m_strand(io_service) {
}
public:
void join(chat_session_ptr);
void leave(chat_session_ptr);
void deliver(const chat_message&);
private:
boost::asio::io_service::strand m_strand;
//std::mutex m_mutex;
std::set<chat_session_ptr> participants_;
enum {
max_recent_msgs = 100 };
chat_message_queue recent_msgs_;
};
//----------------------------------------------------------------------
class chat_session : public std::enable_shared_from_this<chat_session> {
public:
chat_session(tcp::socket socket, chat_room &room)
: socket_(std::move(socket)), room_(room),
m_strand(socket_.get_io_service()) {
}
void start() {
room_.join(shared_from_this());
do_read_header();
}
void deliver(const chat_message &msg) {
// first false
m_strand.post([this

本文详细介绍了如何使用C++和Boost.ASIO库构建一个支持多线程的聊天室系统,包括信号处理、消息传递、会话管理和房间信息更新等关键功能。同时,展示了如何优雅地处理程序退出,确保资源的安全释放。
最低0.47元/天 解锁文章
6万+

被折叠的 条评论
为什么被折叠?



