1 #include "CommandService.hpp"
4 #include "CommandBuffer.hpp"
14 CommandService::CommandService(CLI &cli, unsigned short port)
17 pool.AddConnection(tcp::Socket(port), this);
18 cout << "listening on TCP port " << port << endl;
21 CommandService::~CommandService() {
26 void CommandService::Wait(int timeout) noexcept {
30 bool CommandService::Ready() noexcept {
34 void CommandService::Handle() {
38 void CommandService::Send() {
42 void CommandService::OnRecv(tcp::Socket &serv) {
43 for (tcp::Socket client = serv.Accept(); client; client = serv.Accept()) {
44 pool.AddConnection(move(client), new CommandBuffer(cli));
49 CommandBuffer::CommandBuffer(CLI &cli)
52 , read_buffer(1440, '\0')
57 CommandBuffer::~CommandBuffer() {
62 void CommandBuffer::Error(const string &msg) {
63 // TODO: prefix each line in message/error/broadcast
64 write_buffer += " ! ";
69 void CommandBuffer::Message(const string &msg) {
70 write_buffer += " > ";
75 void CommandBuffer::Broadcast(const string &msg) {
76 // TODO: broadcast should be an operation of the
77 // environment, not the singular context
78 write_buffer += " @ ";
84 void CommandBuffer::OnSend(tcp::Socket &sock) {
85 if (write_buffer.empty()) {
88 size_t len = sock.Send(write_buffer.data(), write_buffer.size());
89 write_buffer.erase(0, len);
92 void CommandBuffer::OnRecv(tcp::Socket &sock) {
93 size_t len = sock.Recv(&read_buffer[0], read_buffer.size() - head);
96 string::iterator begin = read_buffer.begin();
97 string::iterator end = begin + head;
98 string::iterator handled = begin;
100 string::iterator i = find(handled, end, '\n');
102 i = find(handled, end, '\n')
104 string line(handled, i);
105 cli.Execute(*this, line);
108 if (handled == end) {
111 } else if (handled != begin) {
112 // half a line remaining, move it to the start of the buffer
113 move(handled, end, begin);
114 head = distance(handled, end);
118 void CommandBuffer::OnRemove(tcp::Socket &) noexcept {