Unable to Call Tcp Socket Received Callback Function on NS3 - c++

I am new with NS3. I am trying to create a custom application and currently have a difficulty on calling a Socket callback function using socket->SetRecvCallback. This problem occur while I use TcpSocketFactory, another socket such as UDP does not produce this issue.
On main
Ptr<Socket> ns3TcpSocket = Socket::CreateSocket(nodes.Get(0), TcpSocketFactory::GetTypeId());
Custom Tcp Application Class
this->socket->SetRecvCallback(MakeCallback(&CustomTcpApplication::RecvCallback, this));
this->socket->SetSendCallback(MakeCallback(&CustomTcpApplication::WriteUntilBufferFull, this));
My callback function
void CustomTcpApplication::RecvCallback(Ptr<Socket> socket)
{
std::cout << "On Receive Callback Function" << std::endl;
}
void CustomTcpApplication::WriteUntilBufferFull(Ptr<Socket> localSocket, uint32_t txSpace)
{
std::cout << "On Send Callback Function" << std::endl;
}
Also. I read from this answer to implements SetAcceptCallback, ns-3 wlan grid TCP not working while UDP is
this->socket->SetAcceptCallback(MakeNullCallback<bool, Ptr<Socket>, const Address &>(), MakeCallback(&CustomTcpApplication::Accept, this));
Callback Function
void CustomTcpApplication::Accept(Ptr<Socket> socket, const ns3::Address& from)
{
std::cout << "Connection accepted" << std::endl;
socket->SetRecvCallback(MakeCallback(&CustomTcpApplication::MainRecvCallback, this));
}
However, I still cannot log it on the function. Did I missing any step?

I got the same problem today. After tracing codes for hours, I found that there is no native support for TCP data receiving callback.
The tcp-socket-base.cc forks a new TcpSocketBase object for the following data transmission in TcpSocketBase::ProcessListen().The copy constructor of TcpSocketBase resets new socket's callback functions including m_receivedData. That's why data receiving callback doesn't work for TCP.
A simple workaround is to reserve the callback variable from original TcpSocketBase and make m_receivedDataTCP public in src/network/model/socket.h.
TcpSocketBase::TcpSocketBase (const TcpSocketBase& sock)
{
...
m_receivedDataTCP = sock.m_receivedDataTCP;
}

Related

Multithreading issue with UDP Client class implemented using C++

Since I am committed to develop some little audio applications that share audio content over network through the UDP protocol, I am currently drafting the code for a UDP Client class.
This mentioned class should receive the audio content of the other clients connected to network and also send the audio content processed on the local machine; all these contents are exchanged with a server, that works as a kind of content router.
Since audio content is generated by a process() method that is periodically called by the audio application, in order to not loose packets, each audio application should have a kind of UDP listener that is independent from the process() method and that should always be active; they should only share a buffer, or memory allocation, where audio data can be temporary saved and later processed.
Taking all this into account, I coded this method:
void udp_client::listen_to_packets() {
while (udp_client::is_listening) {
if ((udp_client::message_len = recvfrom(udp_client::socket_file_descr, udp_client::buffer, _BUFFER_SIZE, MSG_WAITALL, (struct sockaddr*) &(udp_client::client_struct), &(udp_client::address_len))) < 0) {
throw udp_client_exception("Error on receiving message.");
}
std::cout << "New message received!" << std::endl;
}
std::cout << "Stop listenig for messages!" << std::endl;
}
As you can see, the function uses udp_client::buffer that is the shared memory allocation I previously mentioned. In order to let it be always active, I was thinking to start a new thread or process at class construction and stop its execution at class destruction:
udp_client::udp_client():
is_listening(true) {
std::cout << "Constructing udp_client..." << std::endl;
std::thread listener = std::thread(udp_client::listen_to_packets);
}
udp_client::~udp_client() {
std::cout << "Destructing udp_client..." << std::endl;
udp_client::is_listening = false;
}
Of course, the above listed code doesn't work and as #user4581301 suggested, the listener and is_listening variable definitions have been moved to class attributes:
private:
std::atomic<bool> is_listening;
std::thread listener;
Furthermore the constructor and destructor have been modified a little:
udp_client::udp_client():
listener(&udp_client::listen_to_packets, this),
is_listening(true) {
std::cout << "Constructing udp_client..." << std::endl;
}
udp_client::~udp_client() {
std::cout << "Destructing udp_client..." << std::endl;
udp_client::is_listening = false;
listener.join();
}
Unfortunately, g++ still returns an error, saying that there are not constructors with two arguments for the std::thread class:
error: no matching constructor for initialization of 'std::thread'
listener(&udp_client::listen_to_packets, this)
So, what should I modify to make the code work properly?
Here you can see the implementation of the class (hoping that this link is allowed for Stack Overflow rules):
https://www.dropbox.com/sh/lzxlp3tyvoncvxo/AAApN5KLf3YAsOD0PV7wJJO4a?dl=0

bad_weak_ptr with boost smart pointer

I develop a desktop chat with boost asio and beast (for browser support).
I use this architecture :
But, when building, I have an issue : bad_weak_ptr, I don't know what is wrong :s
Here a link to the source
https://onlinegdb.com/BkFhDGHe4
Update1 :
I remove run() function into constructor and move it into handle_accept function, tcp_server class. like this:
void tcp_server::handle_accept(const boost::system::error_code ec, websocket_session_ptr new_websocket)
{
if (!ec)
{
// Happens when the timer closes the socket
if(ec == boost::asio::error::operation_aborted)
return;
new_websocket->run(); //Here
chatwebsocketsessionpointer session = chat_websocket_session::create(room, new_websocket);
room->join(session);
wait_for_connection();
}
}
I can see the chat_webocket_session is deleted, but still have issue with bad_weak_ptr
Update 2 :
I found where is the issue.
If I never call do_read() function, there is no error, and I can connect to server with ws
If I call it into wait_for_data from chat_websoket_session class, I have issue.
So I must found how call do_read()
Update 3 :
If I do
websocket_session_ptr new_websocket(new websocket_session(std::move(socket)));
acceptor.async_accept(
socket,
boost::bind(
&tcp_server::websocket_accept,
this,
boost::asio::placeholders::error,
new_websocket
));
making ref to : boost beast websocket example, I accept first the socket, and after I accept the websocket with m_ws.async_accept() but I have now Bad file descriptor which means the socket is not open.
P.S: I update the ide URL (GDB online debugger)
You're using the shared pointer to this from inside the constructor:
websocket_session::websocket_session(tcp::socket socket)
: m_ws(std::move(socket))
, strand(socket.get_executor())
{
run();
}
Inside run() you do
void websocket_session::run() {
// Accept the websocket handshake
std::cout << "Accepted connection" << std::endl;
m_ws.async_accept(boost::asio::bind_executor(
strand, std::bind(&websocket_session::on_accept, , std::placeholders::_1)));
}
That uses shared_from_this() which will try to lock the unitialized weak_ptr from enable_shared_from_this. As you can see in the documentation that throws the std::bad_weak_ptr exception (ad. 11)
The documentation to shared_from_this explicitly warns against this:
It is permitted to call shared_from_this only on a previously shared object, i.e. on an object managed by std::shared_ptr (in particular, shared_from_this cannot be called in a constructor).

Server and Client at same time with Boost-Asio

I am an AspNet programmer with 57 years of age. Because I was the only one who worked a little, back in the beginning, with C ++, my bosses asked me to serve a customer who needs a communication agent with very specific characteristics. It can run as a daemon on multiple platforms and be both client and server at times. I do not know enough but I have to solve the problem and found a chance in the Boost / Asio library.
I am new to Boost-Asio and reading the documentation I created a server and a TCP socket client that exchanges messages perfectly and two-way, full duplex.
I read several posts where they asked for the same things I want, but all the answers suggested full duplex as if that meant having a client and a server in the same program. And it's not. The definition of full duplex refers to the ability to write and read from the same connection and every TCP connection is full duplex by default.
I need to make two programs can accept connections initiated by the other. There will be no permanent connection between the two programs. Sometimes one of them will ask for a connection and at other times the other will make this request and both need to be listening, accepting the connection, exchanging some messages and terminating the connection until new request is made.
The server I did seems to get stuck in the process of listening to the port to see if a connection is coming in and I can not continue with the process to be able to create a socket and request a connection with the other program. I need threads but I do not know enough about them.
It'is possible?
As I said I'm new to Boost / Asio and I tried to follow some documents of threads and Coroutines. Then I put the client codes in one method and the server in another.:
int main(int argc, char* argv[])
{
try
{
boost::thread t1(&server_agent);
boost::thread t2(&client_agent);
// wait
t1.join();
t2.join();
return 0;
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
and two Coroutines:
void client_agent() {
parameters param;
param.load();
boost::asio::io_service io_service1;
tcp::resolver resolver(io_service1);
char port[5];
_itoa(param.getNrPortaServComunic(), port, 10);
auto endpoint_iterator = resolver.resolve({ param.getIPServComunicPrincipal(), port });
std::list<client> clients;
client c(io_service1, endpoint_iterator, param);
while (true)
{
BOOL enviada = FALSE;
while (true) {
if (!enviada) {
std::cout << "sending a message\n";
int nr = 110;
message msg(nr, param);
c.write(msg);
enviada = TRUE;
}
}
}
c.close();
}
void server_agent() {
parameters param;
param.load();
boost::asio::io_service io_service1;
std::list<server> servers;
tcp::endpoint endpoint(tcp::v4(), param.getNrPortaAgenteServ());
servers.emplace_back(io_service1, endpoint);
io_service1.run();
}
I used one port to client endpoint and other port to server endpoint. Is it correct? Required?
It starts looking like it's going to work. Each of the methods runs concurrently but then I get a thread allocation error at the io_service1.run (last line of the server_agent method):
boost::exception_detail::clone_impl > at memory location 0x0118C61C.
Any suggestion?
You are describing a UDP client/server application. But your implementation is bound to fail. Think of an asio server or client as always running in a single thread.
The following code is just so you get an idea. I haven't tried to compile it. Client is very similar, but may need a transmit buffer, depends on the app, obviously.
This is a shortened version, so you get the idea. In a final application you way want to add receive timeouts and the likes. The same principles hold for TCP servers, with the added async_listen call. Connected sockets can be stored in shared_ptr, and captured by the lambdas, will destroy almost magically.
Server is basically the same, except there is no constant reading going on. If running both server and client in the same process, you can rely on run() to be looping because of the server, but if not, you'd have to call run() for each connection. run() would exit at the end of the exchange.
using namespace boost::asio; // Or whichever way you like to shorten names
class Server
{
public:
Server(io_service& ios) : ios_(ios) {}
void Start()
{
// create socket
// Start listening
Read();
}
void Read()
{
rxBuffer.resize(1024)
s_.async_receive_from(
buffer(rxBuffer),
remoteEndpoint_,
[this](error_code ec, size_t n)
{
OnReceive(ec, n); // could be virtual, if done this way
});
}
void OnReceive(error_code ec, size_t n)
{
rxBuffer_.resize(n);
if (ec)
{
// error ... stops listen loop
return;
}
// grab data, put in txBuffer_
Read();
s_.async_send_to(
buffer(txBuffer_),
remoteEndpoint_,
[this, msg](error_code ec, size_t n)
{
OnTransmitDone(ec, n);
});
}
void OnTransmitDone(error_code ec, size_t n)
{
// check for error?
txBuffer_.clear();
}
protected:
io_service& ios_;
ip::udp::socket s_;
ip::udp::endpoint remoteEndpoint_; // the other's address/port
std::vector<char> rxBuffer_; // could be any data type you like
std::vector<char> txBuffer_; // idem All access is in one thread, so only
// one needed for simple ask/respond ops.
};
int main()
{
io_service ios;
Server server(ios); // could have both server and client run on same thread
// on same io service this way.
Server.Start();
ios_run();
// or std::thread ioThread([&](){ ios_.run(); });
return 0;
}

"Reloading" a Boost Timer bind to a class method

I've got some trouble with the asio timer.
It is bind to a class method, and when I reload the timer (each time I'm waiting for data or ack), the call back method is called (according to the boost spec).
The problem is that I don't know how to differentiate the cancelation or the completion of the timer.
How should I do that ?
Thanks !
const int TIMER_DURATION = 5000; // ms
tftp_connection::tftp_connection (std::string id,
std::string file_name,
connection_type_enum connection_type,
tftp_server* server,
boost::asio::io_service& io_service)
: timer(io_service, boost::posix_time::milliseconds(TIMER_DURATION)) {
//...
// when sending a block and waiting for acknowledgement
timer.expires_from_now(boost::posix_time::milliseconds(TIMER_DURATION));
timer.async_wait(boost::bind(&tftp_connection::timeout_callback , this));
//...
void tftp_connection::timeout_callback() {
std::cout << "Time Out\n"; }
Looks like you want to check the error code that can be given to the callback if you use the right callback function type. Have a look at:
Boost async_wait example
Your callback should look somehow like this:
void tftp_connection::timeout_callback(const boost::system::error_code& e) {
if(e.value() == ERROR_TIMEOUT) // Or whatever error code you want to check for.
{
std::cout << "Time Out\n";
}
}
in addition, you need to change the bind to:
timer.async_wait(boost::bind(&tftp_connection::timeout_callback , this,boost::asio::placeholders::error));
The boost::asio::placeholders::error tells the bind to create a function which can use the error code as an argument.

Boost::asio - how to interrupt a blocked tcp server thread?

I'm working on a multithreaded application in which one thread acts as a tcp server which receives commands from a client. The thread uses a Boost socket and acceptor to wait for a client to connect, receives a command from the client, passes the command to the rest of the application, then waits again. Here's the code:
void ServerThreadFunc()
{
using boost::asio::ip::tcp;
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), port_no));
for (;;)
{
// listen for command connection
tcp::socket socket(io_service);
acceptor.accept(socket);
// connected; receive command
boost::array<char,256> msg_buf;
socket.receive(boost::asio::buffer(msg_buf));
// do something with received bytes here
}
}
This thread spends most of its time blocked on the call to acceptor.accept(). At the moment, the thread only gets terminated when the application exits. Unfortunately, this causes a crash after main() returns - I believe because the thread tries to access the app's logging singleton after the singleton has been destroyed. (It was like that when I got here, honest guv.)
How can I shut this thread down cleanly when it's time for the application to exit? I've read that a blocking accept() call on a raw socket can be interrupted by closing the socket from another thread, but this doesn't appear to work on a Boost socket. I've tried converting the server logic to asynchronous i/o using the Boost asynchronous tcp echo server example, but that just seems to exchange a blocking call to acceptor::accept() for a blocking call to io_service::run(), so I'm left with the same problem: a blocked call which I can't interrupt. Any ideas?
In short, there are two options:
Change code to be asynchronous (acceptor::async_accept() and async_read), run within the event loop via io_service::run(), and cancel via io_service::stop().
Force blocking calls to interrupt with lower level mechanics, such as signals.
I would recommend the first option, as it is more likely to be the portable and easier to maintain. The important concept to understand is that the io_service::run() only blocks as long as there is pending work. When io_service::stop() is invoked, it will try to cause all threads blocked on io_service::run() to return as soon as possible; it will not interrupt synchronous operations, such as acceptor::accept() and socket::receive(), even if the synchronous operations are invoked within the event loop. It is important to note that io_service::stop() is a non-blocking call, so synchronization with threads that were blocked on io_service::run() must use another mechanic, such as thread::join().
Here is an example that will run for 10 seconds and listens to port 8080:
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <iostream>
void StartAccept( boost::asio::ip::tcp::acceptor& );
void ServerThreadFunc( boost::asio::io_service& io_service )
{
using boost::asio::ip::tcp;
tcp::acceptor acceptor( io_service, tcp::endpoint( tcp::v4(), 8080 ) );
// Add a job to start accepting connections.
StartAccept( acceptor );
// Process event loop.
io_service.run();
std::cout << "Server thread exiting." << std::endl;
}
void HandleAccept( const boost::system::error_code& error,
boost::shared_ptr< boost::asio::ip::tcp::socket > socket,
boost::asio::ip::tcp::acceptor& acceptor )
{
// If there was an error, then do not add any more jobs to the service.
if ( error )
{
std::cout << "Error accepting connection: " << error.message()
<< std::endl;
return;
}
// Otherwise, the socket is good to use.
std::cout << "Doing things with socket..." << std::endl;
// Perform async operations on the socket.
// Done using the socket, so start accepting another connection. This
// will add a job to the service, preventing io_service::run() from
// returning.
std::cout << "Done using socket, ready for another connection."
<< std::endl;
StartAccept( acceptor );
};
void StartAccept( boost::asio::ip::tcp::acceptor& acceptor )
{
using boost::asio::ip::tcp;
boost::shared_ptr< tcp::socket > socket(
new tcp::socket( acceptor.get_io_service() ) );
// Add an accept call to the service. This will prevent io_service::run()
// from returning.
std::cout << "Waiting on connection" << std::endl;
acceptor.async_accept( *socket,
boost::bind( HandleAccept,
boost::asio::placeholders::error,
socket,
boost::ref( acceptor ) ) );
}
int main()
{
using boost::asio::ip::tcp;
// Create io service.
boost::asio::io_service io_service;
// Create server thread that will start accepting connections.
boost::thread server_thread( ServerThreadFunc, boost::ref( io_service ) );
// Sleep for 10 seconds, then shutdown the server.
std::cout << "Stopping service in 10 seconds..." << std::endl;
boost::this_thread::sleep( boost::posix_time::seconds( 10 ) );
std::cout << "Stopping service now!" << std::endl;
// Stopping the io_service is a non-blocking call. The threads that are
// blocked on io_service::run() will try to return as soon as possible, but
// they may still be in the middle of a handler. Thus, perform a join on
// the server thread to guarantee a block occurs.
io_service.stop();
std::cout << "Waiting on server thread..." << std::endl;
server_thread.join();
std::cout << "Done waiting on server thread." << std::endl;
return 0;
}
While running, I opened two connections. Here is the output:
Stopping service in 10 seconds...
Waiting on connection
Doing things with socket...
Done using socket, ready for another connection.
Waiting on connection
Doing things with socket...
Done using socket, ready for another connection.
Waiting on connection
Stopping service now!
Waiting on server thread...
Server thread exiting.
Done waiting on server thread.
When you receive an event that it's time to exit, you can call acceptor.cancel(), which will cancel the pending accept (with an error code of operation_canceled). On some systems, you might also have to close() the acceptor as well to be safe.
If it comes to it, you could open a temporary client connection to it on localhost - that will wake it up. You could even send it a special message so that you can shut down your server from the pub - there should be an app for that:)
Simply call shutdown with native handle and the SHUT_RD option, to cancel the existing receive(accept) operation.
The accepted answer is not exactly correct. Infact #JohnYu answered correctly.
Using blocking API of ASIO is much like using BSD sockets API that ASIO library wraps in its classes.
Problem is boost::asio::ip::tcp::acceptor class does not provide shutdown() functionality so you must do it using "old" sockets API.
Additional note: Make sure acceptor, socket and io_service are not deleted before all threads using it exit. In following code std::shared_ptr is used to keep shared resources alive so user of ApplicationContext class can delete the ApplicationContext object and avoid SEGFAULT crash.
Additional note: pay attention to boost documentation, there are overloaded methods that raise exception and ones that return error code. Original Poster's code used acceptor->accept(socket); without try/catch which would cause program exit instead of normal thread-routine exit and cleanup.
Here is the solution description:
#include <unistd.h> // include ::shutdown() function
// other includes ...
using boost::asio::ip::tcp;
using boost::asio::io_service;
class ApplicationContext {
// Use shared pointer to extend life of resources afer ApplicationContext is deleted
// and running threads can still keep using shared resources
std::shared_ptr<tcp::acceptor> acceptor;
std::shared_ptr<io_service> ioservice;
// called `ServerThreadFunc` in question code example
void AcceptLoopThreadRoutine(int port_no) {
ioservice = std::make_shared<io_service>();
acceptor = std::make_shared<tcp::acceptor>(*ioservice, tcp::endpoint(tcp::v4(), port_no));
try {
for (;;) {
// listen for client connection
tcp::socket socket(*ioservice);
// Note boost::system::system_error is raised when using this overload
acceptor->accept(socket);
// connected receive some data ...
// // boost::array<char,256> msg_buf;
// // socket.receive(boost::asio::buffer(msg_buf));
// do something with received bytes here
}
} catch(std::exception const & exception) {
// boost::system::system_error here indicates clean exit ;)
}
}
void StopAcceptThread() {
if(acceptor) {
// boost::asio::ip::tcp::acceptor does not have shutdown() functionality
// exposed, so we need to do it with this low-level approach
int shutdown_status = shutdown(acceptor->native_handle(), SHUT_RDWR);
}
}
};
Also note that using signals to unblock accept thread is very nasty implementation and temporary client connection on localhost to unblock accept thread is very awkward.
The ASIO is here to help you accomplish everything in single thread with callbacks. If you are mixing threads and ASIO chances are your design is bad.
Additional note: Do not confuse shutdown() and close(). Some systems may allow you to use close() on accept socket to unblock accept loop but this is not portable.