Created
October 11, 2010 22:16
-
-
Save TkTech/621326 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Client::io_callback (ev::io &watcher, int revents) { | |
// Size to expand the buffer on each run | |
static const short buffer_run = 1024; | |
// Data to read | |
if (revents & ev::READ) { | |
// Remember the size of the vector before we change it | |
int old_size = _read_buffer.size(); | |
// Expand the vector | |
_read_buffer.resize(old_size + buffer_run); | |
// Read as much as we can from the socket | |
int bytes_read = recv(_socket, &_read_buffer[old_size], buffer_run, 0); | |
if (bytes_read == -1) { | |
return; | |
} | |
if (bytes_read == 0) { | |
_io.stop(); | |
std::cout << "Client disconnect" << std::endl; | |
Server::instance()->RemoveClient(this); | |
delete this; // Dancin' with the devil | |
return; | |
} | |
// Shrink the vector to consume minimal space | |
// [ToDo] Compare performance benifits of never shrinking the vector | |
_read_buffer.resize(old_size + bytes_read); | |
// Make sure we have enough data to parse the packet | |
if (_read_buffer.size() < _read_required) | |
return; | |
// Attempt to parse any packets in the buffer | |
// [ToDo] Long running tasks such as this should be dispatched to a thread pool | |
_read_required = parse(); | |
} | |
// Interface is available for writing | |
if (revents & ev::WRITE) { | |
if (_write_buffer.size() > 0) { | |
int bytes_sent = send(_socket, &_write_buffer[0], _write_buffer.size(), 0); | |
_write_buffer.erase(_write_buffer.begin(), _write_buffer.begin() + bytes_sent); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment