tcp_connect.cpp
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00014 #ifdef ENABLE_NETWORK
00015
00016 #include "../../stdafx.h"
00017 #include "../../thread/thread.h"
00018
00019 #include "tcp.h"
00020
00022 static SmallVector<TCPConnecter *, 1> _tcp_connecters;
00023
00024 TCPConnecter::TCPConnecter(const NetworkAddress &address) :
00025 connected(false),
00026 aborted(false),
00027 killed(false),
00028 sock(INVALID_SOCKET),
00029 address(address)
00030 {
00031 *_tcp_connecters.Append() = this;
00032 if (!ThreadObject::New(TCPConnecter::ThreadEntry, this, &this->thread)) {
00033 this->Connect();
00034 }
00035 }
00036
00037 void TCPConnecter::Connect()
00038 {
00039 this->sock = this->address.Connect();
00040 if (this->sock == INVALID_SOCKET) {
00041 this->aborted = true;
00042 } else {
00043 this->connected = true;
00044 }
00045 }
00046
00047
00048 void TCPConnecter::ThreadEntry(void *param)
00049 {
00050 static_cast<TCPConnecter*>(param)->Connect();
00051 }
00052
00053 void TCPConnecter::CheckCallbacks()
00054 {
00055 for (TCPConnecter **iter = _tcp_connecters.Begin(); iter < _tcp_connecters.End(); ) {
00056 TCPConnecter *cur = *iter;
00057 if ((cur->connected || cur->aborted) && cur->killed) {
00058 _tcp_connecters.Erase(iter);
00059 if (cur->sock != INVALID_SOCKET) closesocket(cur->sock);
00060 delete cur;
00061 continue;
00062 }
00063 if (cur->connected) {
00064 _tcp_connecters.Erase(iter);
00065 cur->OnConnect(cur->sock);
00066 delete cur;
00067 continue;
00068 }
00069 if (cur->aborted) {
00070 _tcp_connecters.Erase(iter);
00071 cur->OnFailure();
00072 delete cur;
00073 continue;
00074 }
00075 iter++;
00076 }
00077 }
00078
00079 void TCPConnecter::KillAll()
00080 {
00081 for (TCPConnecter **iter = _tcp_connecters.Begin(); iter != _tcp_connecters.End(); iter++) (*iter)->killed = true;
00082 }
00083
00084 #endif