Ejemplo n.º 1
0
//暂不支持timeout清理工作
void NetWork::OnlineUser::check_timeout(std::map<int, int> &timeout_list)
{
	TcpConnection *conn = NULL;
	time_t now = time(0);

	Guard g(_mutex);
	ONLINE_USER_ITER iter = _conns.begin();
	list<int> timeout_conns;
	for (; iter != _conns.end(); ++iter) {
		conn = iter->second;
		conn->add_ref();

		//连接超时检测
		if (conn->getstate() == CONNECTING || conn->getstate() == CRYPTREGING) {
			//连接超时时间是5s
			if (now - conn->get_last_active_time() > 5) {
				LOGW("handle :%d connect timeout", conn->gethandle());
				//!!!注意:close不能再此处调用!否则与外层的_conns循环混到一起了
				//close(conn->gethandle());
				//onClose(conn->gethandle(), SOCKET_ERROR_TIMEOUT);
				conn->set_last_error(SOCKET_ERROR_CONN_TIMEOUT);
				timeout_list.insert(make_pair((int) conn->gethandle(), conn->get_last_error()));
			}
		} else if (conn->getstate() == CONNECTED) {
			//10分钟没有任何响应就强制回收吧
			if (now - conn->get_last_active_time() > 60 * 10) {
				LOGW("handle :%d timeout", conn->gethandle());
				conn->set_last_error(SOCKET_ERROR_TIMEOUT);
				timeout_list.insert(make_pair((int) conn->gethandle(), conn->get_last_error()));
			}
		}

		conn->release();
	}

	return;
}
Ejemplo n.º 2
0
int NetWork::connect(const char *ip, unsigned short port, bool encrypt)
{
	int handle = -1;
	TcpConnection *conn = new TcpConnection(this);

//	if(encrypt) conn->set_encrypt();
	if (conn->connect(ip, port)) {
		if (_online_user.addconn(conn)) {
			_sock_event->add_event(conn, true, true);
			handle = conn->gethandle();
		}
	} else {
		LOGI("NetWork::connect connect fail : %s", strerror(errno));
		//如果连接失败,将底层的网络错误码的负值返回回去;
		handle = (conn->last_sys_errno() * (-1));
		delete conn;
	}

	return handle;
}