2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
9 * @file tcp.h Basic functions to receive and send TCP packets.
12 #ifndef NETWORK_CORE_TCP_H
13 #define NETWORK_CORE_TCP_H
20 /** The states of sending the packets. */
21 enum SendPacketsState
{
22 SPS_CLOSED
, ///< The connection got closed.
23 SPS_NONE_SENT
, ///< The buffer is still full, so no (parts of) packets could be sent.
24 SPS_PARTLY_SENT
, ///< The packets are partly sent; there are more packets to be sent in the queue.
25 SPS_ALL_SENT
, ///< All packets in the queue are sent.
28 /** Base socket handler for all TCP sockets */
29 class NetworkTCPSocketHandler
: public NetworkSocketHandler
{
31 Packet
*packet_queue
; ///< Packets that are awaiting delivery
32 Packet
*packet_recv
; ///< Partially received packet
34 SOCKET sock
; ///< The socket currently connected to
35 bool writable
; ///< Can we write to this socket?
38 * Whether this socket is currently bound to a socket.
39 * @return true when the socket is bound, false otherwise
41 bool IsConnected() const { return this->sock
!= INVALID_SOCKET
; }
43 NetworkRecvStatus
CloseConnection(bool error
= true) override
;
44 virtual void SendPacket(Packet
*packet
);
45 SendPacketsState
SendPackets(bool closing_down
= false);
47 virtual Packet
*ReceivePacket();
49 bool CanSendReceive();
52 * Whether there is something pending in the send queue.
53 * @return true when something is pending in the send queue.
55 bool HasSendQueue() { return this->packet_queue
!= nullptr; }
57 NetworkTCPSocketHandler(SOCKET s
= INVALID_SOCKET
);
58 ~NetworkTCPSocketHandler();
62 * "Helper" class for creating TCP connections in a non-blocking manner
66 std::atomic
<bool> connected
;///< Whether we succeeded in making the connection
67 std::atomic
<bool> aborted
; ///< Whether we bailed out (i.e. connection making failed)
68 bool killed
; ///< Whether we got killed
69 SOCKET sock
; ///< The socket we're connecting with
73 static void ThreadEntry(TCPConnecter
*param
);
76 /** Address we're connecting to */
77 NetworkAddress address
;
80 TCPConnecter(const NetworkAddress
&address
);
81 /** Silence the warnings */
82 virtual ~TCPConnecter() {}
85 * Callback when the connection succeeded.
86 * @param s the socket that we opened
88 virtual void OnConnect(SOCKET s
) {}
91 * Callback for when the connection attempt failed.
93 virtual void OnFailure() {}
95 static void CheckCallbacks();
96 static void KillAll();
99 #endif /* NETWORK_CORE_TCP_H */