KlassischeKeplerKriege/game/session.hpp

74 lines
1.7 KiB
C++
Raw Normal View History

2016-09-27 22:26:36 +00:00
#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:
2016-09-27 23:48:34 +00:00
Session(tcp::socket socket, game::State* state)
: m_socket(std::move(socket))
2016-09-27 22:26:36 +00:00
{
2016-09-27 23:48:34 +00:00
m_state = state;
char c[]="> ";
strcpy(m_snd_data, c);
2016-09-27 22:26:36 +00:00
}
void start()
{
2016-09-27 23:48:34 +00:00
if(m_started) return;
m_started=true;
m_id = m_state->addPlayer();
2016-09-27 22:26:36 +00:00
auto self(shared_from_this());
2016-09-27 23:48:34 +00:00
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)),
2016-09-27 22:26:36 +00:00
[this, self](std::error_code ec, std::size_t /*length*/)
{
if (!ec)
{
do_read();
}
});
}
private:
void do_read()
{
auto self(shared_from_this());
2016-09-27 23:48:34 +00:00
m_socket.async_read_some(asio::buffer(m_rcv_data, max_length),
2016-09-27 22:26:36 +00:00
[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());
2016-09-27 23:48:34 +00:00
asio::async_write(m_socket, asio::buffer(m_snd_data, length),
2016-09-27 22:26:36 +00:00
[this, self](std::error_code ec, std::size_t /*length*/)
{
if (!ec)
{
do_read();
}
});
}
2016-09-27 23:48:34 +00:00
tcp::socket m_socket;
2016-09-27 22:26:36 +00:00
enum { max_length = 1024 };
2016-09-27 23:48:34 +00:00
char m_snd_data[max_length];
char m_rcv_data[max_length];
game::State* m_state;
bool m_started = false;
int m_id;
2016-09-27 22:26:36 +00:00
};