ServerRunner.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * ServerRunner.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "ServerRunner.h"
  12. #include "../lib/VCMIDirs.h"
  13. #include "../lib/CThreadHelper.h"
  14. #include "../server/CVCMIServer.h"
  15. #ifndef VCMI_MOBILE
  16. #include <boost/process/child.hpp>
  17. #include <boost/process/io.hpp>
  18. #endif
  19. ServerThreadRunner::ServerThreadRunner() = default;
  20. ServerThreadRunner::~ServerThreadRunner() = default;
  21. void ServerThreadRunner::start(uint16_t port, bool connectToLobby, std::shared_ptr<StartInfo> startingInfo)
  22. {
  23. server = std::make_unique<CVCMIServer>(port, connectToLobby, true);
  24. if (startingInfo)
  25. {
  26. server->si = startingInfo; //Else use default
  27. }
  28. threadRunLocalServer = boost::thread([this]{
  29. setThreadName("runServer");
  30. server->run();
  31. });
  32. }
  33. void ServerThreadRunner::shutdown()
  34. {
  35. server->setState(EServerState::SHUTDOWN);
  36. }
  37. void ServerThreadRunner::wait()
  38. {
  39. threadRunLocalServer.join();
  40. }
  41. int ServerThreadRunner::exitCode()
  42. {
  43. return 0;
  44. }
  45. #ifndef VCMI_MOBILE
  46. ServerProcessRunner::ServerProcessRunner() = default;
  47. ServerProcessRunner::~ServerProcessRunner() = default;
  48. void ServerProcessRunner::shutdown()
  49. {
  50. child->terminate();
  51. }
  52. void ServerProcessRunner::wait()
  53. {
  54. child->wait();
  55. }
  56. int ServerProcessRunner::exitCode()
  57. {
  58. return child->exit_code();
  59. }
  60. void ServerProcessRunner::start(uint16_t port, bool connectToLobby, std::shared_ptr<StartInfo> startingInfo)
  61. {
  62. boost::filesystem::path serverPath = VCMIDirs::get().serverPath();
  63. boost::filesystem::path logPath = VCMIDirs::get().userLogsPath() / "server_log.txt";
  64. std::vector<std::string> args;
  65. args.push_back("--port=" + std::to_string(port));
  66. args.push_back("--run-by-client");
  67. if(connectToLobby)
  68. args.push_back("--lobby");
  69. std::error_code ec;
  70. child = std::make_unique<boost::process::child>(serverPath, args, ec, boost::process::std_out > logPath);
  71. if (ec)
  72. throw std::runtime_error("Failed to start server! Reason: " + ec.message());
  73. }
  74. #endif