KlassischeKeplerKriege/game/session.hpp
2016-09-28 01:48:34 +02:00

73 lines
1.7 KiB
C++

#pragma once
#include <iostream>
#include <memory>
#include <utility>
#include <asio.hpp>
using asio::ip::tcp;
class Session
: public std::enable_shared_from_this<Session>
{
public:
Session(tcp::socket socket, game::State* state)
: m_socket(std::move(socket))
{
m_state = state;
char c[]="> ";
strcpy(m_snd_data, c);
}
void start()
{
if(m_started) return;
m_started=true;
m_id = m_state->addPlayer();
auto self(shared_from_this());
char hello[] = "\nUse \"n name\" to change name, \"v velocity\" to change velocity, \"c\" to clear past shots or \"q\" to close the connection.\nEverything else is interpreted as a shooting angle.\n\n> ";
asio::async_write(m_socket, asio::buffer(hello, strlen(hello)),
[this, self](std::error_code ec, std::size_t /*length*/)
{
if (!ec)
{
do_read();
}
});
}
private:
void do_read()
{
auto self(shared_from_this());
m_socket.async_read_some(asio::buffer(m_rcv_data, max_length),
[this, self](std::error_code ec, std::size_t length)
{
if (!ec)
{
do_write(length);
}
});
}
void do_write(std::size_t length)
{
auto self(shared_from_this());
asio::async_write(m_socket, asio::buffer(m_snd_data, length),
[this, self](std::error_code ec, std::size_t /*length*/)
{
if (!ec)
{
do_read();
}
});
}
tcp::socket m_socket;
enum { max_length = 1024 };
char m_snd_data[max_length];
char m_rcv_data[max_length];
game::State* m_state;
bool m_started = false;
int m_id;
};