Advertisement
Guest User

client.cpp

a guest
Apr 25th, 2015
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include <functional>
  2. #include <iomanip>
  3. #include <iostream>
  4.  
  5. #include "client.hpp"
  6. #include "handlers.hpp"
  7.  
  8. client::pointer client::create(asio::io_service &ios) {
  9.     return pointer(new client(ios));
  10. }
  11.  
  12. tcp::socket& client::socket() {
  13.     return socket_;
  14. }
  15.  
  16. void client::start() {
  17.     buf = new byte[4096];
  18.  
  19.     socket_.async_receive(asio::buffer(buf, 4096), 0,
  20.         bind(&client::on_receive, shared_from_this(),
  21.         std::placeholders::_1, std::placeholders::_2));
  22. }
  23.  
  24. void client::send(byte* data, size_t len) {
  25.     cryptor->encrypt(data, len);
  26.     cout << "Sent " << socket_.send(asio::buffer(data, len)) << " bytes!" << endl;
  27. }
  28.  
  29. client::client(asio::io_service& ios)
  30.     : socket_(ios) {
  31.     cryptor = new crypt();
  32. }
  33.  
  34. void client::on_receive(const asio::error_code& err, size_t len) {
  35.     if (err) {
  36.         cout << "Client disconnected!" << endl;
  37.        
  38.         delete cryptor;
  39.         //delete[] buf;
  40.         socket_.shutdown(asio::ip::tcp::socket::shutdown_both);
  41.         socket_.close();
  42.  
  43.         return;
  44.     }
  45.  
  46.     cout << "Received packet of length: " << len << endl;
  47.  
  48.     len += prelen;
  49.     prelen = 0;
  50.  
  51.     int32 i = 0;
  52.     size_t plen = 0;
  53.  
  54.     if (plen > len) {
  55.         prelen = len;
  56.  
  57.         socket_.async_receive(asio::buffer(&buf[len], 4096 - len), 0,
  58.             bind(&client::on_receive, shared_from_this(),
  59.             std::placeholders::_1, std::placeholders::_2));
  60.  
  61.         return;
  62.     }
  63.  
  64.     while (i < len) {
  65.         if (!cryptor->is_valid(buf, i))
  66.             return;
  67.  
  68.         plen = cryptor->packet_len(buf, i);
  69.  
  70.         cryptor->decrypt(buf, i, plen);
  71.         uint16 op = *(uint16*)&buf[8];
  72.  
  73.         if ((uint32)handlers[op] != 0xCDCDCDCD) // Valid in Windows debug build only!
  74.             handlers[op](buf, this);
  75.         else
  76.             for (int32 i = 0; i < len; ++i)
  77.                 cout << hex << setfill('0') << setw(2) << (int32)buf[i] << ", " << dec << endl;
  78.  
  79.         i += plen;
  80.     }
  81.  
  82.     socket_.async_receive(asio::buffer(buf, 4096), 0,
  83.         bind(&client::on_receive, shared_from_this(),
  84.         std::placeholders::_1, std::placeholders::_2));
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement