summaryrefslogtreecommitdiff
path: root/server/tcpserver.cpp
blob: 2977b0f3b462c55d5291826fde31daf9082d5bed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "tcpserver.h"

#include <boost/bind.hpp>

TCPServer::TCPServer(boost::asio::io_service& io_service)
	: acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 12345)) {
	
	// Start listening for first connection attempt.
	listen();
}

void TCPServer::listen() {
	Connection::p new_connection = Connection::create(acceptor_.io_service());
	
	acceptor_.async_accept(new_connection->socket,
		boost::bind(&TCPServer::handle_connection, this, new_connection, boost::asio::placeholders::error));
}

void TCPServer::handle_connection(Connection::p connection, const boost::system::error_code& error) {
	if(error) {
		return;
	}
	
	connection->connected();
	
	Message::p m = Message::create();
	m->payload = "Hei morn!";
	
	connection->send(m);
	
	// Start listening for another connection attempt.
	listen();
}