项目作者: gbytegear

项目描述 :
Crossplatform Multi-threading TCP/IP Server
高级语言: C++
项目地址: git://github.com/gbytegear/TcpServer.git
创建时间: 2020-05-20T13:07:38Z
项目社区:https://github.com/gbytegear/TcpServer

开源协议:

下载


TcpServer

Simple Crossplatform Multi-threading TCP/IP Server for exchanging binary data packages

Build library

Required:

  1. # In directory with source code
  2. $ make lib

Usage example:

  1. #include "tcp/include/TcpServer.h"
  2. #include <iostream>
  3. using namespace stcp;
  4. //Parse ip to std::string
  5. std::string getHostStr(const TcpServer::Client& client) {
  6. uint32_t ip = client.getHost ();
  7. return std::string() + std::to_string(int(reinterpret_cast<char*>(&ip)[0])) + '.' +
  8. std::to_string(int(reinterpret_cast<char*>(&ip)[1])) + '.' +
  9. std::to_string(int(reinterpret_cast<char*>(&ip)[2])) + '.' +
  10. std::to_string(int(reinterpret_cast<char*>(&ip)[3])) + ':' +
  11. std::to_string( client.getPort ());
  12. }
  13. TcpServer server(8081,
  14. {1, 1, 1}, // Keep alive{idle:1s, interval: 1s, pk_count: 1}
  15. [](DataBuffer data, TcpServer::Client& client){ // Data handler
  16. std::cout << "Client "<< getHostStr(client) <<" send data [ " << data.size() << " bytes ]: " << (char*)data.data() << '\n';
  17. client.sendData("Hello, client!\0", sizeof("Hello, client!\0"));
  18. },
  19. [](TcpServer::Client& client) { // Connect handler
  20. std::cout << "Client " << getHostStr(client) << " connected\n";
  21. },
  22. [](TcpServer::Client& client) { // Disconnect handler
  23. std::cout << "Client " << getHostStr(client) << " disconnected\n";
  24. },
  25. std::thread::hardware_concurrency() // Thread pool size
  26. );
  27. int main() {
  28. using namespace std::chrono_literals;
  29. try {
  30. //Start server
  31. if(server.start() == TcpServer::status::up) {
  32. std::cout<<"Server listen on port: " << server.getPort() << std::endl
  33. <<"Server handling thread pool size: " << server.getThreadPool().getThreadCount() << std::endl;
  34. server.joinLoop();
  35. return EXIT_SUCCESS;
  36. } else {
  37. std::cout<<"Server start error! Error code:"<< int(server.getStatus()) <<std::endl;
  38. return EXIT_FAILURE;
  39. }
  40. } catch(std::exception& except) {
  41. std::cerr << except.what();
  42. return EXIT_FAILURE;
  43. }
  44. }

Build project example:

Copy the compiled library and the folder with the header files tcp/hdr to the directory with your project and build your project as follows:

  1. $ g++ <your_code.cpp> -I<path/to/header/files> -L<path/to/static_library> -o <name_of_your_programm> -ltcp -lpthread -std=c++17

Development notes:

Binary package structure - [32-bit size header (uint32_t)][Variable size data...]

New client handling way.

In current version used simple implementation of thread pool for server handlers.