1 /* $Id: tcp_connect.cpp 21886 2011-01-22 09:53:15Z rubidium $ */
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
11 * @file tcp_connect.cpp Basic functions to create connections without blocking.
16 #include "../../stdafx.h"
17 #include "../../thread/thread.h"
21 #include "../../safeguards.h"
23 /** List of connections that are currently being created */
24 static SmallVector
<TCPConnecter
*, 1> _tcp_connecters
;
27 * Create a new connecter for the given address
28 * @param address the (un)resolved address to connect to
30 TCPConnecter::TCPConnecter(const NetworkAddress
&address
) :
37 *_tcp_connecters
.Append() = this;
38 if (!ThreadObject::New(TCPConnecter::ThreadEntry
, this, &this->thread
, "ottd:tcp")) {
43 /** The actual connection function */
44 void TCPConnecter::Connect()
46 this->sock
= this->address
.Connect();
47 if (this->sock
== INVALID_SOCKET
) {
50 this->connected
= true;
55 * Entry point for the new threads.
56 * @param param the TCPConnecter instance to call Connect on.
58 /* static */ void TCPConnecter::ThreadEntry(void *param
)
60 static_cast<TCPConnecter
*>(param
)->Connect();
64 * Check whether we need to call the callback, i.e. whether we
65 * have connected or aborted and call the appropriate callback
66 * for that. It's done this way to ease on the locking that
67 * would otherwise be needed everywhere.
69 /* static */ void TCPConnecter::CheckCallbacks()
71 for (TCPConnecter
**iter
= _tcp_connecters
.Begin(); iter
< _tcp_connecters
.End(); /* nothing */) {
72 TCPConnecter
*cur
= *iter
;
73 if ((cur
->connected
|| cur
->aborted
) && cur
->killed
) {
74 _tcp_connecters
.Erase(iter
);
75 if (cur
->sock
!= INVALID_SOCKET
) closesocket(cur
->sock
);
80 _tcp_connecters
.Erase(iter
);
81 cur
->OnConnect(cur
->sock
);
86 _tcp_connecters
.Erase(iter
);
95 /** Kill all connection attempts. */
96 /* static */ void TCPConnecter::KillAll()
98 for (TCPConnecter
**iter
= _tcp_connecters
.Begin(); iter
!= _tcp_connecters
.End(); iter
++) (*iter
)->killed
= true;
101 #endif /* ENABLE_NETWORK */