| 144 | } |
| 145 | |
| 146 | int main(int argc, char* argv[]) |
| 147 | { |
| 148 | // Check command line arguments. |
| 149 | if (argc != 4) |
| 150 | { |
| 151 | std::cerr << |
| 152 | "Usage: websocket-server-coro <address> <port> <threads>\n" << |
| 153 | "Example:\n" << |
| 154 | " websocket-server-coro 0.0.0.0 8080 1\n"; |
| 155 | return EXIT_FAILURE; |
| 156 | } |
| 157 | auto const address = net::ip::make_address(argv[1]); |
| 158 | auto const port = static_cast<unsigned short>(std::atoi(argv[2])); |
| 159 | auto const threads = std::max<int>(1, std::atoi(argv[3])); |
| 160 | |
| 161 | // The io_context is required for all I/O |
| 162 | net::io_context ioc(threads); |
| 163 | |
| 164 | // Spawn a listening port |
| 165 | boost::asio::spawn(ioc, |
| 166 | std::bind( |
| 167 | &do_listen, |
| 168 | std::ref(ioc), |
| 169 | tcp::endpoint{address, port}, |
| 170 | std::placeholders::_1), |
| 171 | // on completion, spawn will call this function |
| 172 | [](std::exception_ptr ex) |
| 173 | { |
| 174 | // if an exception occurred in the coroutine, |
| 175 | // it's something critical, e.g. out of memory |
| 176 | // we capture normal errors in the ec |
| 177 | // so we just rethrow the exception here, |
| 178 | // which will cause `ioc.run()` to throw |
| 179 | if (ex) |
| 180 | std::rethrow_exception(ex); |
| 181 | }); |
| 182 | |
| 183 | // Run the I/O service on the requested number of threads |
| 184 | std::vector<std::thread> v; |
| 185 | v.reserve(threads - 1); |
| 186 | for(auto i = threads - 1; i > 0; --i) |
| 187 | v.emplace_back( |
| 188 | [&ioc] |
| 189 | { |
| 190 | ioc.run(); |
| 191 | }); |
| 192 | ioc.run(); |
| 193 | |
| 194 | return EXIT_SUCCESS; |
| 195 | } |