|
| 1 | +#include <trantor/net/TcpServer.h> |
| 2 | +#include <trantor/utils/Logger.h> |
| 3 | +#include <trantor/net/EventLoopThread.h> |
| 4 | +#include <string> |
| 5 | +#include <iostream> |
| 6 | +using namespace trantor; |
| 7 | +#define USE_IPV6 0 |
| 8 | + |
| 9 | +bool has_ssl(MsgBuffer *buffer) |
| 10 | +{ |
| 11 | + if (buffer->readableBytes() < 3) |
| 12 | + return false; |
| 13 | + const char *data = buffer->peek(); |
| 14 | + unsigned char byte1 = static_cast<unsigned char>(data[0]); |
| 15 | + unsigned char byte2 = static_cast<unsigned char>(data[1]); |
| 16 | + unsigned char byte3 = static_cast<unsigned char>(data[2]); |
| 17 | + return (byte1 == 0x16) && (byte2 == 0x03) && (byte3 == 0x01); |
| 18 | +} |
| 19 | + |
| 20 | +int main() |
| 21 | +{ |
| 22 | + LOG_DEBUG << "test start"; |
| 23 | + Logger::setLogLevel(Logger::kDebug); |
| 24 | + EventLoopThread loopThread; |
| 25 | + loopThread.run(); |
| 26 | +#if USE_IPV6 |
| 27 | + InetAddress addr(8888, true, true); |
| 28 | +#else |
| 29 | + InetAddress addr(8888); |
| 30 | +#endif |
| 31 | + TcpServer server(loopThread.getLoop(), addr, "test"); |
| 32 | + // auto ctx = newSSLServerContext("server.pem", "server.pem", {}); |
| 33 | + LOG_INFO << "start"; |
| 34 | + server.setRecvMessageCallback( |
| 35 | + [](const TcpConnectionPtr &connectionPtr, MsgBuffer *buffer) { |
| 36 | + if (has_ssl(buffer)) |
| 37 | + { |
| 38 | + LOG_DEBUG << "SSL data received"; |
| 39 | + auto policy = |
| 40 | + TLSPolicy::defaultServerPolicy("server.crt", "server.key"); |
| 41 | + connectionPtr->startEncryption(policy, true); |
| 42 | + connectionPtr->forwardToTLSBuffer(buffer); |
| 43 | + return; |
| 44 | + } |
| 45 | + LOG_DEBUG << std::string{buffer->peek(), buffer->readableBytes()}; |
| 46 | + connectionPtr->send(*buffer); |
| 47 | + buffer->retrieveAll(); |
| 48 | + connectionPtr->shutdown(); |
| 49 | + }); |
| 50 | + server.setConnectionCallback([](const TcpConnectionPtr &connPtr) { |
| 51 | + if (connPtr->connected()) |
| 52 | + { |
| 53 | + LOG_DEBUG << "New connection"; |
| 54 | + } |
| 55 | + else if (connPtr->disconnected()) |
| 56 | + { |
| 57 | + LOG_DEBUG << "connection disconnected"; |
| 58 | + } |
| 59 | + }); |
| 60 | + server.setIoLoopNum(3); |
| 61 | + server.start(); |
| 62 | + loopThread.wait(); |
| 63 | +} |
0 commit comments