Beispiel #1
0
int main(int argc, char* argv[])
{
    signal(SIGINT, signalFun);
    if (argc == 2 && 
        (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "/?") == 0))
    {
        cout << "please input like example:" << endl;
        cout << "tcpTest remoteIP remotePort startType" << endl;
        cout << "./tcpTest 0.0.0.0 8081 0" << endl;
        cout << "startType: 0 server, 1 client" << endl;
        return 0;
    }

    if (argc > 1) g_remoteIP = argv[1];
    if (argc > 2) g_remotePort = atoi(argv[2]);
    if (argc > 3) g_startType = atoi(argv[3]);


    
    if (g_startType == 0) ILog4zManager::getPtr()->config("server.cfg");
    else ILog4zManager::getPtr()->config("client.cfg");
    ILog4zManager::getPtr()->start();
    LOGI("g_remoteIP=" << g_remoteIP << ", g_remotePort=" << g_remotePort << ", g_startType=" << g_startType );

    summer = std::shared_ptr<EventLoop>(new EventLoop);
    summer->initialize();

    if (g_startType == 0)
    {
        accepter = std::shared_ptr<TcpAccept>(new TcpAccept());
        accepter->initialize(summer);
        ts = std::shared_ptr<TcpSocket>(new TcpSocket);
        if (!accepter->openAccept(g_remoteIP.c_str(), g_remotePort)) return 0;
        accepter->doAccept(ts, std::bind(OnAcceptSocket, std::placeholders::_1, std::placeholders::_2));
    }
    else
    {
        usedSocket = std::shared_ptr<TcpSocket>(new TcpSocket);
        usedSocket->initialize(summer);
        usedSocket->doConnect(g_remoteIP.c_str(), g_remotePort, std::bind(onConnect, std::placeholders::_1));
    }

    std::function<void()> moniter = [&moniter]()
    {
        cout << "echo=" << sendCount / 5 << endl;
        sendCount = 0;
        summer->createTimer(5000, std::bind(moniter));
    };
    summer->createTimer(5000, std::bind(moniter));

    while (g_runing) summer->runOnce();

    ts.reset();
    accepter.reset();
    usedSocket.reset();

    return 0;
}
Beispiel #2
0
bool SessionManager::openAccepter(AccepterID aID)
{
    auto founder = _mapAccepterOptions.find(aID);
    if (founder == _mapAccepterOptions.end())
    {
        LCE("openAccepter error. not found the Accepter ID extend info. aID=" << aID);
        return false;
    }

    if (founder->second._accepter)
    {
        LCE("openAccepter error. already opened. extend info=" << founder->second);
        return false;
    }
    if (founder->second._listenIP.empty())
    {
        LCE("openAccepter error. no listen IP. extend info=" << founder->second);
        return false;
    }
    
    TcpAcceptPtr accepter = std::make_shared<TcpAccept>();
    if (!accepter->initialize(_summer))
    {
        LCE("openAccept error. extend info=" << founder->second);
        return false;
    }
    if (!accepter->openAccept(founder->second._listenIP, founder->second._listenPort))
    {
        LCE("openAccept error. extend info=" << founder->second);
        return false;
    }
    if (!accepter->doAccept(std::make_shared<TcpSocket>(), 
        std::bind(&SessionManager::onAcceptNewClient, this, std::placeholders::_1, std::placeholders::_2, accepter, founder->second._aID)))
    {
        LCE("openAccept error. extend info=" << founder->second);
        return false;
    }
    founder->second._accepter = accepter;
    return true;
}
Beispiel #3
0
void OnAcceptSocket(NetErrorCode ec, TcpSocketPtr s)
{
    if (ec != NEC_SUCCESS)
    {
        g_runing = false;
        return;
    }
    usedSocket = s;
    usedSocket->initialize(summer);
    usedSocket->doRecv(recvBuffer, recvBufferLen, std::bind(OnServerSocketRecv, std::placeholders::_1, std::placeholders::_2));
    ts = std::shared_ptr<TcpSocket>(new TcpSocket);
    accepter->doAccept(ts, std::bind(OnAcceptSocket, std::placeholders::_1, std::placeholders::_2));
};
Beispiel #4
0
int main(int argc, char* argv[])
{
    signal(SIGINT, signalFun);
    if (argc == 2 && 
        (strcmp(argv[1], "--help") == 0 
        || strcmp(argv[1], "/?") == 0))
    {
        cout << "please input like example:" << endl;
        cout << "tcpTest remoteIP remotePort startType" << endl;
        cout << "./tcpTest 0.0.0.0 8081 0" << endl;
        cout << "startType: 0 server, 1 client" << endl;
        return 0;
    }
    if (argc > 1)
    {
        g_remoteIP = argv[1];
    }
    if (argc > 2)
    {
        g_remotePort = atoi(argv[2]);
    }
    if (argc > 3)
    {
        g_startType = atoi(argv[3]);
    }


    
    if (g_startType == 0)
    {
        ILog4zManager::getPtr()->config("server.cfg");
        ILog4zManager::getPtr()->start();
    }
    else
    {
        ILog4zManager::getPtr()->config("client.cfg");
        ILog4zManager::getPtr()->start();
    }

    LOGI("g_remoteIP=" << g_remoteIP << ", g_remotePort=" << g_remotePort << ", g_startType=" << g_startType );


    

    summer = std::shared_ptr<EventLoop>(new EventLoop);
    summer->initialize();

    if (g_startType == 0)
    {
        accepter = std::shared_ptr<TcpAccept>(new TcpAccept());
        accepter->initialize(summer);
        ts = std::shared_ptr<TcpSocket>(new TcpSocket);
        if (!accepter->openAccept(g_remoteIP.c_str(), g_remotePort))
        {
            return 0;
        }
        
        accepter->doAccept(ts, std::bind(OnAcceptSocket, std::placeholders::_1, std::placeholders::_2));
    }
    else
    {
        usedSocket = std::shared_ptr<TcpSocket>(new TcpSocket);
        usedSocket->initialize(summer);
        usedSocket->doConnect(g_remoteIP.c_str(), g_remotePort, std::bind(onConnect, std::placeholders::_1));
    }
    
    while (g_runing)
    {
        summer->runOnce();
    }
    ts.reset();
    accepter.reset();
    usedSocket.reset();
    //warning: be safe close need:  1.close all established socket. 2. wait all socket recv callback. 3 stop runonce and safe exit.
    return 0;
}
Beispiel #5
0
void SessionManager::onAcceptNewClient(zsummer::network::NetErrorCode ec, const TcpSocketPtr& s, const TcpAcceptPtr &accepter, AccepterID aID)
{
    if (!_running ||  _stopAccept)
    {
        LCI("shutdown accepter. aID=" << aID);
        return;
    }
    auto founder = _mapAccepterOptions.find(aID);
    if (founder == _mapAccepterOptions.end())
    {
        LCE("Unknown AccepterID aID=" << aID);
        return;
    }
    if (ec)
    {
        LCE("doAccept Result Error. ec=" << ec << ", extend=" << founder->second);
        
        auto &&handler = std::bind(&SessionManager::onAcceptNewClient, this, std::placeholders::_1, std::placeholders::_2, accepter, aID);
        auto timer = [accepter, handler]()
        {
            accepter->doAccept(std::make_shared<TcpSocket>(), std::move(handler));
        };
        createTimer(5000, std::move(timer));
        return;
    }

    std::string remoteIP;
    unsigned short remotePort = 0;
    s->getPeerInfo(remoteIP, remotePort);
    
    //! check white list
    //! ---------------------
    if (!founder->second._whitelistIP.empty())
    {
        bool checkSucess = false;
        for (auto white : founder->second._whitelistIP)
        {
            if (remoteIP.size() >= white.size())
            {
                if (remoteIP.compare(0,white.size(), white) == 0)
                {
                    checkSucess = true;
                    break;
                }
            }
        }

        if (!checkSucess)
        {
            LCW("Accept New Client Check Whitelist Failed remoteAdress=" << remoteIP << ":" << remotePort
                << ", extend=" << founder->second);
            accepter->doAccept(std::make_shared<TcpSocket>(), std::bind(&SessionManager::onAcceptNewClient, this, std::placeholders::_1, std::placeholders::_2, accepter, aID));
            return;
        }
        else
        {
            LCI("Accept New Client Check Whitelist Success remoteAdress=" << remoteIP << ":" << remotePort
                << ", extend=" << founder->second);
        }
    }
    
    //! check Max Sessions
    if (founder->second._currentLinked >= founder->second._maxSessions)
    {
        LCW("Accept New Client. Too Many Sessions And The new socket will closed. extend=" << founder->second );
    }
    else
    {
        LCD("Accept New Client. Accept new Sessions. The new socket  remoteAddress=" << remoteIP << ":" << remotePort 
            << ", Aready linked sessions = " << founder->second._currentLinked << ", extend=" << founder->second);
        founder->second._currentLinked++;
        founder->second._totalAcceptCount++;

        _lastSessionID = nextSessionID(_lastSessionID);
        s->initialize(_summer);

        TcpSessionPtr session = std::make_shared<TcpSession>();
        session->getOptions() = founder->second._sessionOptions;
        session->setEventLoop(_summer);
        if (session->attatch(s, aID, _lastSessionID))
        {
            _mapTcpSessionPtr[_lastSessionID] = session;
        }
    }
    
    //! accept next socket.
    accepter->doAccept(std::make_shared<TcpSocket>(), std::bind(&SessionManager::onAcceptNewClient, this, std::placeholders::_1, std::placeholders::_2, accepter, aID));
}
Beispiel #6
0
void SessionManager::onAcceptNewClient(zsummer::network::NetErrorCode ec, const TcpSocketPtr& s, const TcpAcceptPtr &accepter, AccepterID aID)
{
	if (!_running || ! _openAccept)
	{
		LCI("shutdown accepter. aID=" << aID);
		return;
	}
	auto iter = _mapAccepterConfig.find(aID);
	if (iter == _mapAccepterConfig.end())
	{
		LCE("Unknown AccepterID aID=" << aID);
		return;
	}
	if (ec)
	{
		LCE("doAccept Result Error. ec=" << ec << ", traits=" << iter->second.first);
		
		TcpSocketPtr newclient(new zsummer::network::TcpSocket);
		newclient->initialize(_summer);
		auto &&handler = std::bind(&SessionManager::onAcceptNewClient, this, std::placeholders::_1, std::placeholders::_2, accepter, aID);
		auto timer = [accepter, newclient, handler]()
		{
			accepter->doAccept(newclient, std::move(handler));
		};
		createTimer(5000, std::move(timer));
		return;
	}

	std::string remoteIP;
	unsigned short remotePort = 0;
	s->getPeerInfo(remoteIP, remotePort);
	
	//! check white list
	//! ---------------------
	if (!iter->second.first._whitelistIP.empty())
	{
		bool checkSucess = false;
		for (auto white : iter->second.first._whitelistIP)
		{
			if (remoteIP.size() >= white.size())
			{
				if (remoteIP.compare(0,white.size(), white) == 0)
				{
					checkSucess = true;
					break;
				}
			}
		}

		if (!checkSucess)
		{
			LCW("Accept New Client Check Whitelist Failed remoteAdress=" << remoteIP << ":" << remotePort
				<< ", trais=" << iter->second.first);

			TcpSocketPtr newclient(new zsummer::network::TcpSocket);
			newclient->initialize(_summer);
			accepter->doAccept(newclient, std::bind(&SessionManager::onAcceptNewClient, this, std::placeholders::_1, std::placeholders::_2, accepter, aID));
			return;
		}
		else
		{
			LCI("Accept New Client Check Whitelist Success remoteAdress=" << remoteIP << ":" << remotePort
				<< ", trais=" << iter->second.first);
		}
	}
	
	//! check Max Sessions

	if (iter->second.second._currentLinked >= iter->second.first._maxSessions)
	{
		LCW("Accept New Client. Too Many Sessions And The new socket will closed. remoteAddress=" << remoteIP << ":" << remotePort 
			<< ", Aready linked sessions = " << iter->second.second._currentLinked << ", trais=" << iter->second.first);
	}
	else
	{
		LCD("Accept New Client. Accept new Sessions. The new socket  remoteAddress=" << remoteIP << ":" << remotePort 
			<< ", Aready linked sessions = " << iter->second.second._currentLinked << ", trais=" << iter->second.first);
		iter->second.second._currentLinked++;
		iter->second.second._totalAcceptCount++;

		_lastSessionID = nextSessionID(_lastSessionID);
		TcpSessionPtr session(new TcpSession());
		s->initialize(_summer);
		if (session->bindTcpSocketPrt(s, aID, _lastSessionID, iter->second.first))
		{
			_mapTcpSessionPtr[_lastSessionID] = session;
			_totalAcceptCount++;
			MessageDispatcher::getRef().dispatchOnSessionEstablished(session);
		}
	}
	
	//! accept next socket.
	TcpSocketPtr newclient(new zsummer::network::TcpSocket);
	newclient->initialize(_summer);
	accepter->doAccept(newclient, std::bind(&SessionManager::onAcceptNewClient, this, std::placeholders::_1, std::placeholders::_2, accepter,aID));
}