diff --git a/CMakeLists.txt b/CMakeLists.txt index 01eaa53..b02b16e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,6 +7,6 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic") find_package(Boost COMPONENTS serialization system REQUIRED) include_directories(${Boost_INCLUDE_DIR}) -set(SOURCE_FILES main.cpp) +set(SOURCE_FILES server.cpp) add_executable(cpp11NHF2_chat ${SOURCE_FILES}) target_link_libraries(cpp11NHF2_chat ${Boost_LIBRARIES}) \ No newline at end of file diff --git a/server.cpp b/server.cpp new file mode 100644 index 0000000..849a604 --- /dev/null +++ b/server.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +#include +#include +#include +using namespace boost::asio; +using namespace boost::asio::ip; + + + +io_service ioservice; +tcp::endpoint tcpendpoint{tcp::v4(), 2222}; +tcp::acceptor tcpacceptor{ioservice, tcpendpoint}; +tcp::socket sock{ioservice}; +std::vector alldata; +std::array data; + + +void read_handler(const boost::system::error_code& ec, std::size_t transferred) +{ + if (!ec) + { + std::cout.write(data.data(), transferred); + for (int i = 0; i < transferred; ++i) + alldata.push_back(data[i]); + sock.async_read_some(buffer(data), read_handler); + } +} + +void write_handler(const boost::system::error_code& ec, std::size_t transferred) +{ + if (!ec) + { + tcp::endpoint remoteendpoint = sock.remote_endpoint(); + address ip = remoteendpoint.address(); + + std::cout << transferred + << " bytes transferred to " + << ip.to_string() << ":" << remoteendpoint.port() + << std::endl; + + sock.async_read_some(buffer(data), read_handler); + } +} + +void accept_handler(const boost::system::error_code& ec) +{ + if (!ec) + { + std::time_t now = std::time(nullptr); + std::string time(std::ctime(&now)); + async_write(sock, buffer(time), write_handler); + } +} + + +int main() +{ + tcpacceptor.listen(); + tcpacceptor.async_accept(sock, accept_handler); + + // work, so the server does not stop listening + auto work = std::make_shared(ioservice); + ioservice.run(); + + return EXIT_SUCCESS; +} \ No newline at end of file