jean
jean

Reputation: 1

C++ Can I make boost::asio connection socket without timer?

I have a window server socket and a Linux client socket. Client connect to server and send a message. After, the server will call a external executable. The problem is : when server is not available, Client is blocking with timeout at connect function, But I don't want it. I hope if the connection is not made, client socket will be closed straight away.

Somebody can give me some advice?

Upvotes: 0

Views: 625

Answers (1)

DeVadder
DeVadder

Reputation: 1404

Warning: Pseudo-Code ahead.

You can do that. But it is not as straight forward as you might hope. You need to use async_connect() from your client to not block. Then you also need a deadline_timer set to whatever timeout you deem appropriate. Zero will not work, you need to give the async_connect() some time. But i guess one or two seconds should be fine.

The timers handler will then have to cancel() all async operations on the socket (you need to make sure that is only the connect, use more sockets if needed).

Mind the socket will not be closed by that. Ideally you will close it in the handler of the async_connect whenever the passed error_code indicates a negative result. For example, if it was canceled, the handler will be called with OPERATION_ABORTED as error_code.

Of course, if you check only for that, you could as well close() the socket in the timers handler after the cancel(). But that would leave you with an open socket whenever the async_connect failed for some other reason.

I would assume from your question that you want your socket to get closed whenever the async_connect() passes any error_code but SUCCESS. And SUCCESS is the only error_code implicitly converted to 0 when used as a boolean, so checking for that in your handler is easy. ^^

Do not forget to cancel the deadline_timer in the handler of the async_connect() and to make sure the timers handler was not called with OPERATION_ABORTED before it closes the socket. ^^

Upvotes: 1

Related Questions