• Welcome to Andy's Workshop Forums. Please login or sign up.
 
April 28, 2024, 12:41:43 am

News:

SMF - Just Installed!


TCP Server - sending after a connection accept

Started by Ozflip, November 04, 2014, 03:23:40 pm

Previous topic - Next topic

Ozflip

November 04, 2014, 03:23:40 pm Last Edit: November 04, 2014, 08:35:22 pm by Ozflip
So, to my next (probably simple) question....

I'm playing with the net_tcp_server example. I've worke out how to use the notifications such as onAccept (and yes, I now own the connection!  ;D ) but I'm wondering how to go about a simple task.

If I want to immediately send a message to the client on connection, what's the right way to do that? I've tried sending the message in the onAccept handler (after calling event.accept of course) but that doesn't seem to be the right way:


    void onAccept(TcpAcceptEvent& event)
    {
        *_outputStream << "TCP client requested connection.\r\n";
    event.acceptConnection();

        uint32_t actuallySent;
    event.connection->send("Hello\r\n",8,actuallySent,0);
    }


The call above seems to lock the TCP connection up, and noting is sent. I'm guessing the connection isn't in the right state or something.

Phil

Andy Brown

My immediate thought is that you're in an IRQ context and are calling a synchronous method that itself will need to wait for IRQ-related stuff to happen hence the lock-up. Setting a state flag in onAccept() and checking for it in your main loop is one way of doing this but there are better ways...

The net_tcp_server example, which I'm sure you've already seen, is the best example of how to handle a multi-connection server. Subclass TcpConnection and implement handleWrite() and handleRead(). Create yourself a state variable in your subclass which at its simplest could be 'bool _greetingSent' and set to false. You will get a callback to handleWrite() any time that a write to the peer is possible so the first time it happens is when the connection is accepted and enters the ESTABLISHED state. In your handleWrite() check your state variable and if it's 'false' then write out the greeting message (or whatever) and set the state to true. In reality you'll be maintaining a more complex state machine here based on your protocol.

The net_ftp_server example shows a much more complete example using the same basic building blocks.
It's worse than that, it's physics Jim!

Ozflip

Thanks .. I misunderstood the nature of handleWrite - that makes more sense.