|
| 1 | +#include "WebSocketHttpImp.h" |
| 2 | + |
| 3 | +#include <stdexcept> |
| 4 | + |
| 5 | +#include "WebSocketDemoConfig.h" |
| 6 | +#include "util/tc_common.h" |
| 7 | +#include "util/tc_file.h" |
| 8 | +#include "util/tc_http.h" |
| 9 | + |
| 10 | +using namespace std; |
| 11 | +using namespace tars; |
| 12 | + |
| 13 | +namespace |
| 14 | +{ |
| 15 | +string renderClientPage(const string &templateContent, const WebSocketDemoConfig &config) |
| 16 | +{ |
| 17 | + string page = templateContent; |
| 18 | + page = TC_Common::replace(page, "__WS_PORT__", TC_Common::tostr(config.websocketEndpoint.getPort())); |
| 19 | + page = TC_Common::replace(page, "__WS_PATH__", config.websocketPath); |
| 20 | + return page; |
| 21 | +} |
| 22 | +} |
| 23 | + |
| 24 | +void WebSocketHttpImp::initialize() |
| 25 | +{ |
| 26 | + const WebSocketDemoConfig config = loadWebSocketDemoConfig(); |
| 27 | + if (!TC_File::isFileExist(config.clientPageFile)) |
| 28 | + { |
| 29 | + throw runtime_error("client page not found: " + config.clientPageFile); |
| 30 | + } |
| 31 | + |
| 32 | + _clientPageContent = renderClientPage(TC_File::load2str(config.clientPageFile), config); |
| 33 | + if (_clientPageContent.empty()) |
| 34 | + { |
| 35 | + throw runtime_error("client page is empty: " + config.clientPageFile); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +void WebSocketHttpImp::destroy() |
| 40 | +{ |
| 41 | +} |
| 42 | + |
| 43 | +int WebSocketHttpImp::doRequest(TarsCurrentPtr current, vector<char> &buffer) |
| 44 | +{ |
| 45 | + (void)buffer; |
| 46 | + |
| 47 | + TC_HttpRequest request; |
| 48 | + request.decode(current->getRequestBuffer()); |
| 49 | + |
| 50 | + const string requestPath = request.getRequestUrl().empty() ? "/" : request.getRequestUrl(); |
| 51 | + |
| 52 | + TC_HttpResponse response; |
| 53 | + if (requestPath == "/" || requestPath == "/index.html") |
| 54 | + { |
| 55 | + response.setResponse(200, "OK", _clientPageContent); |
| 56 | + response.setContentType("text/html; charset=utf-8"); |
| 57 | + } |
| 58 | + else |
| 59 | + { |
| 60 | + response.setResponse(404, "Not Found", "WebSocketServer example page not found."); |
| 61 | + response.setContentType("text/plain; charset=utf-8"); |
| 62 | + } |
| 63 | + |
| 64 | + response.setConnection("close"); |
| 65 | + |
| 66 | + const string encoded = response.encode(); |
| 67 | + current->sendResponse(encoded.c_str(), (uint32_t)encoded.size()); |
| 68 | + return 0; |
| 69 | +} |
0 commit comments