Boost::ASIO cannot write back to client from server - c++

I have a couple questions regarding Boost ASIO.
I'm running into a problem where my clients can connect to a server, and asynchronously send data, but cannot receive anything back. The async_write callback gets error: "The file handle supplied is not valid". I find this strange for a couple reasons:
When the client connects initially, I check socket.isOpen() on the server, and it returns true.
The fact that the client can still send data makes me think that it's a server side problem, or a firewall problem (which I find odd because the server and client are both on the same computer (I'm using "localhost" to connect for now).
Some more info...
TCP Sockets.
I'm using Boost and Allegro side-by-side, and both Boost and Allegro threads are being used. I have my io_service running in a Boost thread like so (server and client):
boost::asio::io_service::work work( io_service );
boost::thread io_thread( boost::bind( &boost::asio::io_service::run, &io_service ) );
and that's being called before I even create the sockets.
The Allegro threads hold the Allegro event loops, nothing special there.
I'd like to not have to post source code, it's pretty large and complicated, and I'd rather not try and simplify it to a basic case. I can if it's necessary though.
My sockets are wrapped by a class in which a shared pointer is created and passed around rather than than a regular pointer (Not sure if that matters, I'm new to Boost).
Thank you for any help you can provide in determining why I cannot write back to the clients I have connected to.
Neil
EDIT: Requested code segments:
async_read/write (server) and callback functions:
void ServerConnection::async_read()
{
if( this->m_socket.is_open() == false )
{
std::cerr << "socket closed... (read)\n";
}
boost::asio::async_read( this->m_socket,
boost::asio::buffer( &m_input, sizeof( m_input ) ),
boost::bind( &ServerConnection::read_callback,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred ) );
}
void ServerConnection::async_write(const packet_list &packet, packet_id id, uint8_t rr)
{
this->m_output.data = packet;
this->m_output.head.opcode = id;
this->m_output.head.sender_id = 0;
this->m_output.head.response_required = rr;
if( this->m_socket.is_open() )
{
std::cerr << "socket closed... (write)\n";
}
boost::asio::async_write( this->m_socket,
boost::asio::buffer( &m_output, sizeof( m_output ) ),
boost::bind( &ServerConnection::write_callback,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred ) );
}
void ServerConnection::read_callback( const boost::system::error_code &error,
size_t /*read_count*/ )
{
if( error )
{
std::cerr << "Error reading: " << error.message() << std::endl;
return;
}
std::cerr << "Server reading data...\n";
if( this->m_event_dispatcher != nullptr )
{
ALLEGRO_EVENT event;
if( m_input.head.opcode == C_ACCEPT )
{
event.type = 513;
}
else
{
event.type = 512;
event.user.data1 = (intptr_t)&m_input;
}
al_emit_user_event( this->m_event_dispatcher, &event, nullptr );
}
else
{
std::cerr << "Why is this null....\n";
}
async_read();
}
void ServerConnection::write_callback(const boost::system::error_code &error,
size_t /*write_count*/ )
{
// After a write, we don't need to do anything except error checking.
if( error.value() )
{
std::cerr << "Error writing to client. " << error.message() << std::endl;
}
}

Related

Boost asio udp socket sending to different ip address

I have one udp server receiving messages from multiple remote clients. When it receives one message, I copy the endpoint and reply to the client at the same IP address on port 5000 where each client is listening.
I have tried multiple debbuging strategies, and printing the endpoint right before I send the reply message gives me the correct IP address and port.
The sender:
std::cout << udp_remote_endpoint.address().to_string();
std::string str(packet.begin(), packet.end());
std::cout << str << std::endl;
io_service.post(
[this, packet]()
{
udp_socket.async_send_to(
boost::asio::buffer(packet),
udp_remote_endpoint,
boost::bind(
&uds::handle_write,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);
}
);
On the receiver, I get the udp_remote_endpoint and before sending, I set the socket endpoint:
new_addr.endpoint = socket.get_udp_remote_endpoint();
new_addr.endpoint.port(5000);
socket.set_udp_remote_endpoint(new_addr.endpoint);
For example, this output:
192.168.1.131K-131-1559147491761155
Is actually sending to the IP 192.168.1.130. The message contents are correct "K-131-1559147491761155"
Solved!
I removed the io_service.post and it worked!
`std::cout << udp_remote_endpoint.address().to_string();
std::string str(packet.begin(), packet.end());
std::cout << str << std::endl;
//io_service.post(
// [this, packet]()
// {
udp_socket.async_send_to(
boost::asio::buffer(packet),
udp_remote_endpoint,
boost::bind(
&uds::handle_write,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);
// }
//);`

Boost Socket goes belly-up on close()

We have a C++ application that talks to a server. It sends two messages to it, and the server responds to each message with another message. We're using Boost, but the Boost Socket--the entire application--barfs when we attempt to close the socket.
Here's the general idea of what we're doing:
encode the message (change it into a string)
open socket
send message
check the bytes sent
check the return message
shutdown & close the socket
Since we send two messages, we do it in a loop (just two iterations, obviously).
We know exactly where the error is since, if we remove that line, it works fine. It's on step 5. Unfortunately, that's kind of an important step. We can't find what we're doing wrong how to fix it.
Here's the code:
bool ReallyImportantService::sendMessages( int messageNum ) {
// ...some error-checking here...
bool successCode = false;
for( int i = 0; i < 2; ++i ) {
successCode = false;
unique_ptr<boost::asio::ip::tcp::socket> theSocket = connect();
if( theSocket == nullptr ) {
theLogger->error( "Could not create socket, could not send input messageNum to service" );
return successCode;
}
string message = encodeMessage( messageNum );
// send the message
boost::system::error_code error;
size_t bytesSent = boost::asio::write(*theSocket,
boost::asio::buffer(message),
boost::asio::transfer_all(), error);
// inspect the result
if( !messageNumSendSuccessful(message.length(), bytesSent) ) {
return successCode;
}
// Get the response message
string response;
boost::system::error_code e;
boost::asio::streambuf buffer;
// this is step #5 above, the line that kills it. But it responds with no errors
boost::asio::read_until(*theSocket, buffer, "\0", e);
if( e.value() == boost::system::errc::success ) {
istream str(&buffer);
getline(str, response);
// validate response
successCode = messageAckIsValid( response, messageNum );
}
else {
theLogger->error( "Got erroneous response from server when sending messageNum" );
}
// close it all up
boost::system::error_code eShut;
theSocket->shutdown(boost::asio::socket_base::shutdown_type::shutdown_both, eShut);
// We never get an error code here, all clean
try {
boost::system::error_code ec;
// This is where it all goes belly-up. It doesn't throw an exception, doesn't return an
// error-code. Stepping through, we can see the call stack shows a Segmentation fault,
// but we don't know what could be causing this.
theSocket->close( ec );
}
catch(boost::system::system_error& se) {
theLogger->error( "sendMessages() barfed on close! " + string(se.what()) );
}
catch( ... ) {
theLogger->error( "sendMessages() barfed on close! " );
}
}
return successCode;
}
string ReallyImportantService::encodeMessage( int messageNum ) {
// Encode the message
stringstream ss;
ss << "^FINE=";
ss << to_string(messageNum) << "\n";
string message = ss.str();
theLogger->info( message );
return message;
}
unique_ptr<boost::asio::ip::tcp::socket> ReallyImportantService::connect() {
// Addresses from configuration
string address( server_ip );
string port( server_port );
// Resolve the IP address
boost::asio::io_service ioService;
boost::asio::ip::tcp::resolver resolver(ioService);
boost::asio::ip::tcp::resolver::query query(address, port);
boost::asio::ip::tcp::resolver::iterator ep_iterator = resolver.resolve(query);
// create the socket
unique_ptr<boost::asio::ip::tcp::socket> theSocket = make_unique<boost::asio::ip::tcp::socket>(ioService);
// not sure if this is necessary, but couldn't hurt; we do reuse the IP address the second time around
boost::system::error_code ec;
theSocket->set_option(boost::asio::socket_base::reuse_address(true), ec);
// Connect
try {
boost::asio::connect(*theSocket, ep_iterator);
} catch(const boost::system::system_error &e){
theSocket = nullptr;
theLogger->error( "Exception while attempting to create socket: " + string(e.what()) );
} catch(const exception &e){
theSocket = nullptr;
theLogger->error( "Exception while attempting to create socket: " + string(e.what()) );
}
return theSocket;
}
Here's the call stack we get when it errors-out:
(Suspended : Signal : SIGSEGV:Segmentation fault)
pthread_mutex_lock() at 0x7ffff7bc8c30
boost::asio::detail::posix_mutex::lock() at posix_mutex.hpp:52 0x969072
boost::asio::detail::scoped_lock<boost::asio::detail::posix_mutex>::scoped_lock() at scoped_lock.hpp:36 0x980b66
boost::asio::detail::epoll_reactor::free_descriptor_state() at epoll_reactor.ipp:517 0x96c6fa
boost::asio::detail::epoll_reactor::deregister_descriptor() at epoll_reactor.ipp:338 0x96bccc
boost::asio::detail::reactive_socket_service_base::close() at reactive_socket_service_base.ipp:103 0xb920aa
boost::asio::stream_socket_service<boost::asio::ip::tcp>::close() at stream_socket_service.hpp:151 0xb975e0
boost::asio::basic_socket<boost::asio::ip::tcp, boost::asio::stream_socket_service<boost::asio::ip::tcp> >::close() at basic_socket.hpp:339 0xb94f0d
ReallyImportantService::sendMessages() at ReallyImportantService.cc:116 0xb8ce19
<...more frames...>
We created a minimal implementation that just:
Creates the socket
Shuts down the socket
Closes the socket
And it works perfectly. We put it in a loop and we can go for dozens of iterations without any problems.
We're using Eclipse CDT and gcc to compile.
Any idea what might be going on?
You've broken the cardinal rule.
An io_service must outlive all objects created on it.
Your connect() function creates an io_service, creates a socket on it and returns the socket (wrapped in a unique_ptr). Then the io_service is destroyed.
From that point forward, all bets are off because the socket will use a the socket service object associated with the io_service you just destroyed. This socket service is now just memory with undefined values in it. You're (un)lucky the program got this far before the segfault.
In general you will need one io_service per application. All objects that need it should carry a reference to it.
Your connect function then becomes:
bool connect(boost::asio::ip::tcp& theSocket) {
// Addresses from configuration
string address( server_ip );
string port( server_port );
// Resolve the IP address
boost::asio::ip::tcp::resolver resolver(theSocket.get_io_service());
boost::asio::ip::tcp::resolver::query query(address, port);
boost::asio::ip::tcp::resolver::iterator ep_iterator = resolver.resolve(query);
// not sure if this is necessary, but couldn't hurt; we do reuse the IP address the second time around
boost::system::error_code ec;
theSocket.set_option(boost::asio::socket_base::reuse_address(true), ec);
// Connect
try {
boost::asio::connect(theSocket, ep_iterator);
} catch(const boost::system::system_error &e){
theSocket = nullptr;
theLogger->error( "Exception while attempting to create socket: " + string(e.what()) );
return false;
} catch(const exception &e){
theSocket = nullptr;
theLogger->error( "Exception while attempting to create socket: " + string(e.what()) );
return false;
}
return true;
}
bool sendMessages(boost::asio::io_service& ios, int messageNum)
{
boost::asio::ip::tcp::socket theSocket(ios);
auto ok = connect(theSocket);
// ... carry on ...
}
Prefer to hold references to sockets etc whenever possible. Wrapping them in a unique_ptr is a confusing extra layer of indirection.
As of c++11 and recent versions of boost, asio sockets are moveable. You can return them by value as opposed to passing in a reference as I have done.
I notice that you have a mixture of exception and non-exception error handling in the code. You probably want to stick to one or the other (in my view exception-based error handling is cleaner, but this is not a universal view).

Got packet received from the group I do not join

I am a beginner of multicast programming. I am using boost::asio to scribe some multicast data.
I wrote a program with the code
boost::array<char,1500> _receiveBuf;
void WaitForNextRead()
{
_receiveSocket->async_receive_from(
boost::asio::buffer(_receiveBuf, 1500),
_receiveEndPoint,
boost::bind(
&AsyncReadHandler,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void AsyncReadHandler(
const boost::system::error_code& error, // Result of operation.
std::size_t bytes_transferred // Number of bytes received.
)
{
std::cout << _receiveEndPoint.address() << ":" << _receiveEndPoint.port() << ":" << std::string(_receiveBuf.c_array(), bytes_transferred) << "\n";
WaitForNextRead();
}
int main()
{
std::string address;
int port;
std::cin >> address;
std::cin >> port;
boost::asio::io_service ioService;
_receiveSocket = new udp::socket( ioService );
_receiveSocket->open( udp::v4() );
_receiveSocket->set_option( udp::socket::reuse_address(true) );
_receiveSocket->bind( udp::endpoint( address::from_string("0.0.0.0"), port ) );
_receiveSocket->set_option( multicast::join_group( address::from_string(address) ) );
_receiveEndPoint.address(address::from_string(address));
_receiveEndPoint.port(port);
WaitForNextRead();
ioService.run();
return 0;
}
My instance A is joining: 239.1.1.1:12345
My instance B is joining: 239.1.127.1:12345
It is very weird that both instance A and B will get the message from both address!!
Did I miss out some socket option?
PS:
Here is my routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
224.0.0.0 * 240.0.0.0 U 0 0 0 eth1
I think I found the answer.
Refer to:
http://man7.org/linux/man-pages/man7/ip.7.html
https://bugzilla.redhat.com/show_bug.cgi?id=231899
Linux has a bug that the broadcast IP_ADD_MEMBERSHIP is a global action to all sockets even when part of another process. We need to set the option IP_MULTICAST_ALL to zero (0) to fix this problem.

boost asio - write equivalent piece of code

I have this piece of code using standard sockets:
void set_fds(int sock1, int sock2, fd_set *fds) {
FD_ZERO (fds);
FD_SET (sock1, fds);
FD_SET (sock2, fds);
}
void do_proxy(int client, int conn, char *buffer) {
fd_set readfds;
int result, nfds = max(client, conn)+1;
set_fds(client, conn, &readfds);
while((result = select(nfds, &readfds, 0, 0, 0)) > 0) {
if (FD_ISSET (client, &readfds)) {
int recvd = recv(client, buffer, 256, 0);
if(recvd <= 0)
return;
send_sock(conn, buffer, recvd);
}
if (FD_ISSET (conn, &readfds)) {
int recvd = recv(conn, buffer, 256, 0);
if(recvd <= 0)
return;
send_sock(client, buffer, recvd);
}
set_fds(client, conn, &readfds);
}
I have sockets client and conn and I need to "proxy" traffic between them (this is part of a socks5 server implementation, you may see https://github.com/mfontanini/Programs-Scripts/blob/master/socks5/socks5.cpp). How can I achieve this under asio ?
I must specify that until this point both sockets were operated under blocking mode.
Tried to use this without success:
ProxySession::ProxySession(ba::io_service& ioService, socket_ptr socket, socket_ptr clientSock): ioService_(ioService), socket_(socket), clientSock_(clientSock)
{
}
void ProxySession::Start()
{
socket_->async_read_some(boost::asio::buffer(data_, 1),
boost::bind(&ProxySession::HandleProxyRead, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void ProxySession::HandleProxyRead(const boost::system::error_code& error,
size_t bytes_transferred)
{
if (!error)
{
boost::asio::async_write(*clientSock_,
boost::asio::buffer(data_, bytes_transferred),
boost::bind(&ProxySession::HandleProxyWrite, this,
boost::asio::placeholders::error));
}
else
{
delete this;
}
}
void ProxySession::HandleProxyWrite(const boost::system::error_code& error)
{
if (!error)
{
socket_->async_read_some(boost::asio::buffer(data_, max_length),
boost::bind(&ProxySession::HandleProxyRead, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
else
{
delete this;
}
}
The issue is that if I do ba::read(*socket_, ba::buffer(data_,256)) I can read data that comes from my browser client through socks proxy but in the version from above ProxySession::Start does not lead to HandleProxyRead being called in any circumstances.
I don't really need an async way of exchanging data here, it;s just that I've come by with this solution here. Also from where I called ProxySession->start from code I needed to introduce a sleep because otherwise the thread context from which this was executing was being shut down.
*Update 2 * See below one of my updates. The question block is getting too big.
The problem ca be solved by using asynchronous write/read functions in order to have something similar with presented code. Basically use async_read_some()/async_write() - or other async functions in these categories. Also in order for async processing to work one must call boost::asio::io_service.run() that will dispatch completion handler for async processing.
I have managed to come with this. This solution solves the problem of "data exchange" for the 2 sockets (that must happen acording to socks5 server proxy) but it is very compute intensive. Any ideas ?
std::size_t readable = 0;
boost::asio::socket_base::bytes_readable command1(true);
boost::asio::socket_base::bytes_readable command2(true);
try
{
while (1)
{
socket_->io_control(command1);
clientSock_->io_control(command2);
if ((readable = command1.get()) > 0)
{
transf = ba::read(*socket_, ba::buffer(data_,readable));
ba::write(*clientSock_, ba::buffer(data_,transf));
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}
if ((readable = command2.get()) > 0)
{
transf = ba::read(*clientSock_, ba::buffer(data_,readable));
ba::write(*socket_, ba::buffer(data_,transf));
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}
}
}
catch (std::exception& ex)
{
std::cerr << "Exception in thread while exchanging: " << ex.what() << "\n";
return;
}

Acceptor and Problems with Async_Accept

See code. :P
I am able to receive new connections before async_accept() has been called. My delegate function is also never called so I can't manage any connections I receive, rendering the new connections useless. ;)
So here's my question. Is there a way to prevent the Boost ASIO acceptor from getting new connections on its own and only getting connections from async_accept()?
Thanks!
AlexSocket::AlexSocket(boost::asio::io_service& s): myService(s)
{
//none at the moment
connected = false;
listening = false;
using boost::asio::ip::tcp;
mySocket = new tcp::socket(myService);
}
AlexSocket::~AlexSocket()
{
delete mySocket;
}
bool AlexSocket::StartListening(int port)
{
bool didStart = false;
if (!this->listening)
{
//try to listen
acceptor = new tcp::acceptor(this->myService);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
//CAN GET NEW CONNECTIONS HERE (before async_accept is called)
acceptor->listen();
didStart = true; //probably change?
tcp::socket* tempNewSocket = new tcp::socket(this->myService);
//acceptor->async_accept(*tempNewSocket, boost::bind(&AlexSocket::NewConnection, this, tempNewSocket, boost::asio::placeholders::error) );
}
else //already started!
return false;
this->listening = didStart;
return didStart;
}
//this function is never called :(
void AlexSocket::NewConnection(tcp::socket* s, const boost::system::error_code& error)
{
cout << "New Connection Made" << endl;
//Start new accept async
tcp::socket* tempNewSocket = new tcp::socket(this->myService);
acceptor->async_accept(*tempNewSocket, boost::bind(&AlexSocket::NewConnection, this, tempNewSocket, boost::asio::placeholders::error) );
}
bool AlexSocket::ConnectToServer(std::string toConnectTo, string port)
{
if (connected)
return false;
this->serverConnectedTo = toConnectTo;
this->serverPort = port;
ip::tcp::resolver resolver(myService);
ip::tcp::resolver::query newQuery(toConnectTo, port);
ip::tcp::resolver::iterator myIter = resolver.resolve(newQuery);
ip::tcp::resolver::iterator end;
//error
boost::system::error_code error = boost::asio::error::host_not_found;
//try each endpoint
bool connected = false;
while (error && myIter != end)
{
ip::tcp::endpoint endpoint = *myIter++;
std::cout << endpoint << std::endl;
mySocket->close();
mySocket->connect(*myIter, error);
if (error)
{
//try to connect, if it didn't work return false
cout << "Did not Connect" << endl << error << endl;
}
else
{
//was able to connect
cout << "Connected!" << endl;
connected = true;
}
myIter++;
}
this->connected = connected;
return connected;
}
EDIT:
I've changed my code to reflect what the answers so far have said. I am passing in an io_service to the ctor of my class. As you can see below, main is NOT calling run on the service, so I would assume that nothing should be able to connect right?
I have put my debugger on the listen() line and went to "canyouseeme.org". Typed in 57422 and hit Connect. Couldn't. Ran the listen() line. Was able to connect. This shouldn't be possible right? Like never? :(
No idea what to do anymore. main() is below.
int main()
{
boost::asio::io_service s;
AlexSocket test(s);
test.StartListening(57422);
test.ConnectToServer("localhost", "57422");
cout << "Enter something to quit" << endl;
int a2;
cin >> a2;
return 0;
}
So here's my question. Is there a way to prevent the Boost ASIO acceptor from getting new connections on its own and only getting connections from async_accept()?
Why do you think this is happening? If you posted the complete code, that would greatly help. When I take your snippet and put a boilerplate main and io_service::run() around it, everything works fine.
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <iostream>
using namespace boost::asio;
class Socket {
public:
Socket(
io_service& io_service
) :
_io_service( io_service ),
_acceptor( new ip::tcp::acceptor(io_service) )
{
}
bool start(int port)
{
//try to listen
ip::tcp::endpoint endpoint(ip::tcp::v4(), port);
_acceptor->open(endpoint.protocol());
_acceptor->set_option(ip::tcp::acceptor::reuse_address(true));
_acceptor->bind(endpoint);
//CAN GET NEW CONNECTIONS HERE (before async_accept is called)
_acceptor->listen();
ip::tcp::socket* temp = new ip::tcp::socket( _io_service );
_acceptor->async_accept(
*temp,
boost::bind(
&Socket::NewConnection,
this,
temp,
boost::asio::placeholders::error
)
);
}
void NewConnection(
ip::tcp::socket* s,
const boost::system::error_code& error
)
{
std::cout << "New Connection Made" << std::endl;
//Start new accept async
ip::tcp::socket* temp = new ip::tcp::socket( _io_service );
_acceptor->async_accept(
*temp,
boost::bind(
&Socket::NewConnection,
this,
temp,
boost::asio::placeholders::error
)
);
}
private:
io_service& _io_service;
ip::tcp::acceptor* _acceptor;
};
int
main()
{
io_service foo;
Socket sock( foo );
sock.start(1234);
foo.run();
return 0;
}
compile and run:
macmini:~ samm$ g++ -lboost_system accept.cc
macmini:~ samm$ ./a.out
New Connection Made
telnet from another terminal
macmini:~ samm$ telnet 127.0.0.1 1234
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
I think you are mixing different things here.
On the one hand, you are creating a socket for data exchange. A socket is nothing more than an endpoint of an inter-process communication flow across a computer network. Your boost::asio::tcp::socket uses the TCP-protocoll for the communication; but in general, a socket can use other protocols. For opening a tcp-socket, one uses generally the sequence open-bind-listen-accept on the host.
On the other hand, you analyse the (underlying) TCP-connection.
So there are two different things here. While for the socket the connection is considered "established" only after the "accept" of the host, the underlying TCP-connection is already established after the client connects to a listening socket. (One the server side, that connection is put on a stack, from which it is dequeue when you call accept()).
So the only way to prohibit connection in your case, is not to call listen().
If you are truly getting a new connection at the point when you call acceptor->listen() then I am puzzled by that. What are you using to determine whether you've gotten a connection or not? The io_service is typically quite "reactive" in that it only reacts to events that it has been explicitly told to react to.
In your example above, the only thing I see that would cause a "new connection" to be initiated is calling async_accept. Additionally, what you described makes little sense from a low-level sockets standpoint (using BSD sockets, typically you must call bind, listen, and accept in that order, and only then can a new connection be made).
My suspicion is that you've actually got some faulty logic somewhere. Who calls StartListening and how often is it called (it should only need to be called once). You've gone through a bunch of extra effort to setup your acceptor object that's usually not necessary in Asio - you can typically just use the acceptor constructor to create an acceptor with all the parameters you need, and then just call async_accept:
acceptor = new tcp::acceptor(
this->myService,
boost::asio::ip::tcp::endpoint(
boost::asio::ip::tcp::v4(),
port),
true);
tcp::socket* tempNewSocket = new tcp::socket(this->myService);
acceptor->async_accept(
*tempNewSocket,
boost::bind(
&AlexSocket::NewConnection,
this,
tempNewSocket,
boost::asio::placeholders::error) );