Przeglądaj źródła

调整为Ctrl+C退出服务器

johnclot69 6 dni temu
rodzic
commit
edd3bb1663
2 zmienionych plików z 22 dodań i 6 usunięć
  1. 1 1
      src/common/Message.h
  2. 21 5
      src/server/apps/gameserver/Main.cpp

+ 1 - 1
src/common/Message.h

@@ -8,7 +8,7 @@
 struct Message {
     uint32_t cmd;               // 消息协议号
     int code = 0;               // 错误码(例如 200 表示 OK)
-    std::string message = "";   // 消息提示
+    std::string message;        // 消息提示
     std::unordered_map<std::string, msgpack::object> data; // 消息内容
 
     // 使用 MSGPACK_DEFINE_MAP 宏生成序列化代码

+ 21 - 5
src/server/apps/gameserver/Main.cpp

@@ -1,4 +1,5 @@
 #include <boost/asio.hpp>
+#include <boost/asio/signal_set.hpp>
 #include <iostream>
 #include "WebsocketServer.h"
 #include <boost/asio/ip/tcp.hpp>
@@ -7,17 +8,32 @@ using tcp = boost::asio::ip::tcp;
 
 int main() {
     try {
+        // 创建一个 io_context 用于信号处理
+        boost::asio::io_context io_context;
+        // 用于捕获 Ctrl+C (SIGINT) 和 SIGTERM 信号
+        boost::asio::signal_set signals(io_context, SIGINT, SIGTERM);
+
         // 监听地址和端口:127.0.0.1:9000
         tcp::endpoint endpoint(tcp::v4(), 9000);
         WebsocketServer server( endpoint);
         server.start();
 
-        // 阻塞主线程
-        std::cout << "Press Enter to stop the server..." << std::endl;
-        std::cin.get();
+        // 异步等待信号,收到信号后停止服务器并退出 io_context
+        signals.async_wait(
+            [&](const boost::system::error_code& error, int signal_number) {
+                if (!error) {
+                    std::cout << "\nSignal " << signal_number << " received. Stopping server..." << std::endl;
+                    server.stop();
+                    io_context.stop();
+                }
+            }
+        );
 
-        server.stop();
-    } catch (const std::exception& ex) {
+        std::cout << "Server is running. Press Ctrl+C to exit..." << std::endl;
+        // 阻塞等待信号到来
+        io_context.run();
+    }
+    catch (const std::exception& ex) {
         std::cerr << "[Main] Exception: " << ex.what() << std::endl;
     }
     return 0;