ServerRunner.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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)
  22. {
  23. server = std::make_unique<CVCMIServer>(port, connectToLobby, true);
  24. threadRunLocalServer = boost::thread([this]{
  25. setThreadName("runServer");
  26. server->run();
  27. });
  28. }
  29. void ServerThreadRunner::shutdown()
  30. {
  31. server->setState(EServerState::SHUTDOWN);
  32. }
  33. void ServerThreadRunner::wait()
  34. {
  35. threadRunLocalServer.join();
  36. }
  37. int ServerThreadRunner::exitCode()
  38. {
  39. return 0;
  40. }
  41. #ifndef VCMI_MOBILE
  42. ServerProcessRunner::ServerProcessRunner() = default;
  43. ServerProcessRunner::~ServerProcessRunner() = default;
  44. void ServerProcessRunner::shutdown()
  45. {
  46. child->terminate();
  47. }
  48. void ServerProcessRunner::wait()
  49. {
  50. child->wait();
  51. }
  52. int ServerProcessRunner::exitCode()
  53. {
  54. return child->exit_code();
  55. }
  56. void ServerProcessRunner::start(uint16_t port, bool connectToLobby)
  57. {
  58. boost::filesystem::path serverPath = VCMIDirs::get().serverPath();
  59. boost::filesystem::path logPath = VCMIDirs::get().userLogsPath() / "server_log.txt";
  60. std::vector<std::string> args;
  61. args.push_back("--port=" + std::to_string(port));
  62. args.push_back("--run-by-client");
  63. if(connectToLobby)
  64. args.push_back("--lobby");
  65. std::error_code ec;
  66. child = std::make_unique<boost::process::child>(serverPath, args, ec, boost::process::std_out > logPath);
  67. if (ec)
  68. throw std::runtime_error("Failed to start server! Reason: " + ec.message());
  69. }
  70. #endif