I'm struggling with running tcp server in different thread. So I have sth like that:
#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
class TcpServer
{
private:
boost::asio::io_context& io_context_;
boost::asio::ip::tcp::acceptor acceptor_;
boost::asio::ip::tcp::socket socket_;
public:
TcpServer(boost::asio::io_context& io_context)
: io_context_{io_context}
, socket_(io_context_)
, acceptor_(io_context_, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 512))
{
acceptor_.accept(socket_);
std::string message = make_daytime_string();
boost::system::error_code ignored_error;
socket_.write_some(boost::asio::buffer(message), ignored_error);
}
};
int main()
{
boost::asio::io_context io_cont;
std::thread t([&io_cont] ()
{
TcpServer server(io_cont);
});
std::cout << "I want to display it while server is still running";
t.join();
return 0;
}
Basically this TcpServer is running all the time until it gets connection, sends datetime and then exits. What I want to do is:
- Run the server
- Keep processing my things in main function
- Send command
nc 127.0.0.1 512 - program ends