revise network system

This commit is contained in:
Eduardo Bart
2011-08-15 21:30:31 -03:00
parent be15b1820d
commit f87b475f49
26 changed files with 291 additions and 242 deletions

View File

@@ -47,4 +47,7 @@
#include "util/rect.h"
#include "util/size.h"
// easy typing for _1, _2, ...
using namespace std::placeholders;
#endif

View File

@@ -6,9 +6,6 @@
void LuaInterface::registerFunctions()
{
// easy typing _1, _2, ...
using namespace std::placeholders;
// UIWidget
g_lua.registerClass<UIWidget>();
g_lua.bindClassStaticFunction<UIWidget>("create", &UIWidget::create);

View File

@@ -1,125 +1,147 @@
#include "connection.h"
#include "networkmanager.h"
#include <framework/core/eventdispatcher.h>
#include <boost/asio.hpp>
static asio::io_service ioService;
asio::io_service g_ioService;
Connection::Connection() :
m_timer(ioService),
m_resolver(ioService),
m_socket(ioService)
m_readTimer(g_ioService),
m_writeTimer(g_ioService),
m_resolver(g_ioService),
m_socket(g_ioService)
{
}
Connection::~Connection()
{
disconnect();
m_connected = false;
}
void Connection::poll()
{
ioService.poll();
ioService.reset();
g_ioService.poll();
g_ioService.reset();
}
void Connection::connect(const std::string& host, uint16 port, const ConnectCallback& connectCallback)
void Connection::terminate()
{
g_ioService.stop();
}
void Connection::connect(const std::string& host, uint16 port, const SimpleCallback& connectCallback)
{
m_connected = false;
m_connectCallback = connectCallback;
asio::ip::tcp::resolver::query query(host, fw::unsafe_cast<std::string>(port));
m_resolver.async_resolve(query, std::bind(&Connection::onResolve, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
m_resolver.async_resolve(query, std::bind(&Connection::onResolve, shared_from_this(), _1, _2));
m_timer.expires_from_now(boost::posix_time::seconds(2));
m_timer.async_wait(std::bind(&Connection::onTimeout, shared_from_this(), std::placeholders::_1));
m_readTimer.expires_from_now(boost::posix_time::seconds(READ_TIMEOUT));
m_readTimer.async_wait(std::bind(&Connection::onTimeout, shared_from_this(), _1));
}
void Connection::disconnect()
void Connection::close()
{
m_socket.close();
if(!m_connected)
return;
m_readTimer.cancel();
m_writeTimer.cancel();
if(m_socket.is_open()) {
m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
m_socket.close();
}
m_connected = false;
}
void Connection::send(uint8* buffer, uint16 size)
void Connection::write(uint8* buffer, uint16 size)
{
if(!m_connected)
return;
m_writeTimer.cancel();
asio::async_write(m_socket,
asio::buffer(buffer, size),
std::bind(&Connection::onSend, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
asio::buffer(buffer, size),
std::bind(&Connection::onWrite, shared_from_this(), _1, _2));
m_timer.expires_from_now(boost::posix_time::seconds(2));
m_timer.async_wait(std::bind(&Connection::onTimeout, shared_from_this(), std::placeholders::_1));
m_writeTimer.expires_from_now(boost::posix_time::seconds(WRITE_TIMEOUT));
m_writeTimer.async_wait(std::bind(&Connection::onTimeout, shared_from_this(), _1));
}
void Connection::recv(uint16 bytes, uint32 timeout, const RecvCallback& callback)
void Connection::read(uint16 bytes, const RecvCallback& callback)
{
m_readTimer.cancel();
if(!m_connected)
return;
m_recvCallback = callback;
m_recvSize = bytes;
asio::async_read(m_socket,
asio::buffer(m_recvBuffer, bytes),
std::bind(&Connection::onRecv, shared_from_this(), std::placeholders::_1));
asio::buffer(m_recvBuffer, bytes),
std::bind(&Connection::onRecv, shared_from_this(), _1));
if(timeout > 0) {
m_timer.expires_from_now(boost::posix_time::seconds(timeout));
m_timer.async_wait(std::bind(&Connection::onTimeout, shared_from_this(), std::placeholders::_1));
}
m_readTimer.expires_from_now(boost::posix_time::seconds(READ_TIMEOUT));
m_readTimer.async_wait(std::bind(&Connection::onTimeout, shared_from_this(), _1));
}
void Connection::onResolve(const boost::system::error_code& error, asio::ip::tcp::resolver::iterator endpointIterator)
{
m_readTimer.cancel();
if(!error) {
m_socket.async_connect(*endpointIterator, std::bind(&Connection::onConnect, shared_from_this(), _1));
m_readTimer.expires_from_now(boost::posix_time::seconds(READ_TIMEOUT));
m_readTimer.async_wait(std::bind(&Connection::onTimeout, shared_from_this(), _1));
} else
handleError(error);
}
void Connection::onConnect(const boost::system::error_code& error)
{
m_readTimer.cancel();
m_connected = true;
if(!error) {
if(m_connectCallback)
g_dispatcher.addEvent(m_connectCallback);
} else
handleError(error);
}
void Connection::onWrite(const boost::system::error_code& error, size_t)
{
m_writeTimer.cancel();
if(error)
handleError(error);
}
void Connection::onRecv(const boost::system::error_code& error)
{
m_readTimer.cancel();
if(!error) {
if(m_recvCallback)
g_dispatcher.addEvent(std::bind(m_recvCallback, m_recvBuffer, m_recvSize));
} else
handleError(error);
}
void Connection::onTimeout(const boost::system::error_code& error)
{
if(error != asio::error::operation_aborted)
handleError(error);
}
void Connection::handleError(const boost::system::error_code& error)
{
logTraceDebug(error.message());
close();
if(m_errorCallback)
g_dispatcher.addEvent(std::bind(m_errorCallback, error));
}
void Connection::onResolve(const boost::system::error_code& error, asio::ip::tcp::resolver::iterator endpointIterator)
{
m_timer.cancel();
if(error) {
if(m_errorCallback)
g_dispatcher.addEvent(std::bind(m_errorCallback, error));
return;
}
m_socket.async_connect(*endpointIterator, std::bind(&Connection::onConnect, shared_from_this(), std::placeholders::_1));
m_timer.expires_from_now(boost::posix_time::seconds(2));
m_timer.async_wait(std::bind(&Connection::onTimeout, shared_from_this(), std::placeholders::_1));
}
void Connection::onConnect(const boost::system::error_code& error)
{
m_timer.cancel();
if(error) {
if(m_errorCallback)
g_dispatcher.addEvent(std::bind(m_errorCallback, error));
return;
}
if(m_connectCallback)
g_dispatcher.addEvent(m_connectCallback);
}
void Connection::onSend(const boost::system::error_code& error, size_t)
{
m_timer.cancel();
if(error) {
if(m_errorCallback)
g_dispatcher.addEvent(std::bind(m_errorCallback, error));
return;
}
}
void Connection::onRecv(const boost::system::error_code& error)
{
m_timer.cancel();
if(error) {
if(m_errorCallback)
g_dispatcher.addEvent(std::bind(m_errorCallback, error));
return;
}
if(m_recvCallback)
g_dispatcher.addEvent(std::bind(m_recvCallback, m_recvBuffer, m_recvSize));
}

View File

@@ -8,40 +8,49 @@ class Connection : public std::enable_shared_from_this<Connection>, boost::nonco
{
typedef std::function<void(boost::system::error_code&)> ErrorCallback;
typedef std::function<void(uint8*, uint16)> RecvCallback;
typedef std::function<void()> ConnectCallback;
enum {
READ_TIMEOUT = 10,
WRITE_TIMEOUT = 10
};
public:
Connection();
virtual ~Connection();
static void init();
static void poll();
static void terminate();
void connect(const std::string& host, uint16 port, const ConnectCallback& connectCallback);
void disconnect();
void send(uint8* buffer, uint16 size);
void recv(uint16 bytes, uint32 timeout, const RecvCallback& callback);
void connect(const std::string& host, uint16 port, const SimpleCallback& connectCallback);
void close();
void write(uint8* buffer, uint16 size);
void read(uint16 bytes, const RecvCallback& callback);
void setErrorCallback(const ErrorCallback& errorCallback) { m_errorCallback = errorCallback; }
void setRecvCallback(const RecvCallback& recvCallback) { m_recvCallback = recvCallback; }
bool isConnected() const { return m_connected; }
private:
void onTimeout(const boost::system::error_code& error);
void onResolve(const boost::system::error_code& error, asio::ip::tcp::resolver::iterator endpointIterator);
void onConnect(const boost::system::error_code& error);
void onSend(const boost::system::error_code& error, size_t);
void onWrite(const boost::system::error_code& error, size_t);
void onRecv(const boost::system::error_code& error);
void onTimeout(const boost::system::error_code& error);
void handleError(const boost::system::error_code& error);
SimpleCallback m_connectCallback;
ErrorCallback m_errorCallback;
ConnectCallback m_connectCallback;
RecvCallback m_recvCallback;
asio::deadline_timer m_timer;
asio::deadline_timer m_readTimer;
asio::deadline_timer m_writeTimer;
asio::ip::tcp::resolver m_resolver;
asio::ip::tcp::socket m_socket;
uint8 m_recvBuffer[65538];
uint16 m_recvSize;
RecvCallback m_recvCallback;
bool m_connected;
};
#endif

View File

@@ -1,10 +1,9 @@
#include "protocol.h"
#include "connection.h"
Protocol::Protocol() :
m_connection(new Connection)
Protocol::Protocol() : m_connection(new Connection)
{
m_connection->setErrorCallback(std::bind(&Protocol::onError, this, std::placeholders::_1));
m_connection->setErrorCallback(std::bind(&Protocol::onError, this, _1));
m_xteaEncryptionEnabled = false;
m_checksumEnabled = true;
}
@@ -14,41 +13,48 @@ void Protocol::connect(const std::string& host, uint16 port)
m_connection->connect(host, port, std::bind(&Protocol::onConnect, asProtocol()));
}
void Protocol::disconnect()
{
m_connection->close();
}
void Protocol::send(OutputMessage& outputMessage)
{
// Encrypt
// encrypt
if(m_xteaEncryptionEnabled)
xteaEncrypt(outputMessage);
// Set checksum
// set checksum
uint32 checksum = getAdlerChecksum(outputMessage.getBuffer() + OutputMessage::DATA_POS, outputMessage.getMessageSize());
outputMessage.setWritePos(OutputMessage::CHECKSUM_POS);
outputMessage.addU32(checksum);
// Set size
// set size
uint16 messageSize = outputMessage.getMessageSize();
outputMessage.setWritePos(OutputMessage::HEADER_POS);
outputMessage.addU16(messageSize);
// Send
m_connection->send(outputMessage.getBuffer(), outputMessage.getMessageSize());
// send
m_connection->write(outputMessage.getBuffer(), outputMessage.getMessageSize());
}
void Protocol::recv()
{
m_inputMessage.reset();
m_connection->recv(InputMessage::HEADER_LENGTH, 2, std::bind(&Protocol::internalRecvHeader, asProtocol(), std::placeholders::_1, std::placeholders::_2));
m_connection->read(InputMessage::HEADER_LENGTH, std::bind(&Protocol::internalRecvHeader, asProtocol(), _1, _2));
}
void Protocol::internalRecvHeader(uint8* buffer, uint16 size)
{
memcpy(m_inputMessage.getBuffer() + InputMessage::HEADER_POS, buffer, size);
// read message size
uint16 dataSize = m_inputMessage.getU16();
m_inputMessage.setMessageSize(dataSize);
m_connection->recv(dataSize, 5, std::bind(&Protocol::internalRecvData, asProtocol(), std::placeholders::_1, std::placeholders::_2));
// schedule read for message data
m_connection->read(dataSize, std::bind(&Protocol::internalRecvData, asProtocol(), _1, _2));
}
void Protocol::internalRecvData(uint8* buffer, uint16 size)
@@ -59,7 +65,7 @@ void Protocol::internalRecvData(uint8* buffer, uint16 size)
uint32 checksum = getAdlerChecksum(m_inputMessage.getBuffer() + InputMessage::DATA_POS, m_inputMessage.getMessageSize() - InputMessage::CHECKSUM_LENGTH);
if(m_inputMessage.getU32() != checksum) {
// error
logError("Checksum is invalid.");
logError("ERROR: got a network message with invalid checksum");
return;
}
}
@@ -70,27 +76,12 @@ void Protocol::internalRecvData(uint8* buffer, uint16 size)
onRecv(m_inputMessage);
}
void Protocol::onError(const boost::system::error_code& err)
{
std::stringstream message;
logError("PROTOCOL ERROR: ", err.message());
message << "Boost error: " << err.message();
// invalid hostname
// connection timeouted
// displays a dialog, finish protocol
callLuaField("onError", message.str());
}
bool Protocol::xteaDecrypt(InputMessage& inputMessage)
{
// FIXME: this function has not been tested yet
uint16 messageSize = inputMessage.getMessageSize() - InputMessage::CHECKSUM_LENGTH;
if(messageSize % 8 != 0) {
logDebug("not valid encrypted message size");
logError("ERROR: invalid encrypted network message");
return false;
}
@@ -113,7 +104,7 @@ bool Protocol::xteaDecrypt(InputMessage& inputMessage)
int tmp = inputMessage.getU16();
if(tmp > inputMessage.getMessageSize() - 4) {
logDebug("not valid unencrypted message size");
logDebug("ERROR: invalid decrypted a network message");
return false;
}

View File

@@ -13,14 +13,17 @@ public:
Protocol();
void connect(const std::string& host, uint16 port);
void disconnect();
void send(OutputMessage& outputMessage);
void recv();
void internalRecvHeader(uint8* buffer, uint16 size);
void internalRecvData(uint8* buffer, uint16 size);
virtual void onConnect() = 0;
virtual void onRecv(InputMessage& inputMessage) = 0;
virtual void onError(const boost::system::error_code& err);
virtual void onError(const boost::system::error_code& err) = 0;
ProtocolPtr asProtocol() { return std::static_pointer_cast<Protocol>(shared_from_this()); }