- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
#ifndef _header_hpp_included_
#define _header_hpp_included_
#include <iostream>
#include <cstdio>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/lexical_cast.hpp>
enum { recv_buffer_size = 13 };
enum { send_buffer_size = 13 };
volatile size_t counter = 0;
void client_readed(
boost::asio::ip::tcp::socket&,
char*,
FILE*,
const boost::system::error_code&
);
void client_read(
boost::asio::ip::tcp::socket& sock,
FILE* out
) {
char* buf = new char[recv_buffer_size];
boost::asio::async_read(
sock,
boost::asio::buffer(buf, recv_buffer_size),
boost::bind(
&client_readed,
boost::ref(sock),
buf,
out,
boost::asio::placeholders::error));}
void client_readed(
boost::asio::ip::tcp::socket& sock,
char* buf,
FILE* out,
const boost::system::error_code& e) {
if ( e ) {
if ( !counter ) return;
std::cout << "read handler: " << e.message() << std::endl;
return;
}
fwrite(buf, recv_buffer_size, 1, out);
counter--;
#ifdef _my_debug_
printf("client_readed(): %s", buf);
fflush(stdout);
#endif
static size_t idx = 0;
size_t tmp = 0;
char* p = strchr(buf, ':');
if ( p ) {
p++;
sscanf(p, "%8d", &tmp);
} else
throw std::runtime_error("input data error!");
delete[] buf;
if ( idx != tmp ) {
std::ostringstream os;
os << "read error. expected " << idx << " get " << tmp;
throw std::runtime_error(os.str());
}
idx++;
client_read(sock, out);
}
void writen(
char*,
FILE*,
const boost::system::error_code&
);
void start_write(
boost::asio::ip::tcp::socket& sock,
char* buf,
FILE* out) {
counter++;
boost::asio::async_write(
sock,
boost::asio::buffer(buf, send_buffer_size),
boost::bind(
&writen,
buf,
out,
boost::asio::placeholders::error)
);
}