Esempio n. 1
0
void ConnectionHandler::Start()
{
	bool running = true;
	std::cout << "Start() called [connection handler]" << std::endl;
	/*socket_.async_read_some(boost::asio::buffer(data_, max_length), 
							boost::bind(&ConnectionHandler::HandleRead, 
										this, 
										boost::asio::placeholders::error, 
										boost::asio::placeholders::bytes_transferred));*/
	boost::system::error_code error;
	int bytes_read;
	while (running) 
	{
		bytes_read = socket_.read_some(boost::asio::buffer(data_, max_length), error); // if error, there could be a disconnect
		//bytes_read = socket_.read_some(boost::asio::buffer(w_data_, max_length), error);
		cout << data_[4] << L'\n';
		if (!error) 
		{
			std::cout << "bytes read" << bytes_read << std::endl;
			HandleRead(error, bytes_read);
			delete data_;
			data_ = new char[max_length];
		}
		else
		{
			running = false;
			delete this;
		}
	}
}
Esempio n. 2
0
bool MemcachedClient::Request(const char* buf, int len, CmdType& t, map<string, string>& resdata, map<string, int>& flags){
  t = CMD_NOTDEF;
  cur_recv_len_ = 0;
  total_recv_len_ = 0;
  res_.clear();
  int retry = 2;
  
  //服务端重启的情况下,会导致send失败,需要重新链接再send
  while(retry-- > 0){
    if(!CheckConnect()){
      return false;
    }
    if(Send(buf, len)){
      break;
    }else{
      connected_ = false;
      continue;
    }
  }
  int pos = 0;
  bool suc = false;
  int count = 0;
  while(true){
    struct pollfd fds;
    fds.fd=sockfd_;
    fds.events=POLLIN;
    int res = poll(&fds, 1, timeout_);
    if(res <= 0){
      //printf("@@@@@@@@3 %d\n", count);
      if(res < 0){
        MCE_WARN("MemcachedClient::Request --> poll err, " << res << " " << strerror(errno));
      }else{
        MCE_INFO("MemcachedClient::Request --> poll timeout, " << res << " " << strerror(errno));
      }
      return false;
    }else if(res==1){
      bool s = HandleRead(t, resdata, flags);
      //printf("HandleRead %d %d\n", s, t);
      if(!s){
        //printf("@@@@@@@@4\n");
        return false;
      }
      if(t==CMD_VALUE || t==CMD_NOTDEF){
        count++;
        continue;
      }else if(t==CMD_END || t==CMD_STORED || t==CMD_NOT_STORED || t==CMD_DELETED || t==CMD_NOT_FOUND){
        return true; 
      }else{
        MCE_WARN("MemcachedClient::Request --> parser err " << t);
        return false;
      }
    }
    count++;
  }
  //printf("@@@@@@@@ 2222\n");
  MCE_WARN("MemcachedClient::Request --> parser err3 " << t);
  return false;
}
Esempio n. 3
0
void EventLoop(int fd, void *handle)
{
  intf_thread_t *intf = (intf_thread_t*)handle;
  intf_sys_t *sys = intf->p_sys;

  sys->line = (char *)malloc(MAX_LINE * sizeof(char));

  while(1) {
    struct pollfd ufd = { .fd = fd, .events = POLLIN | POLLOUT, };
    
    if(poll(&ufd, 1, 1000) <= 0) /* block for 1s so we don't spin */
      continue;
    
    if(ufd.revents & POLLIN) {
      int rv = HandleRead(handle);
      if(rv != 0) {
	msg_Err(intf, "Read error: %s", strerror(rv));
	break;
      }
    } else if(ufd.revents & POLLOUT) {
      int rv = HandleWrite(handle);
      if(rv != 0) {
	msg_Err(intf, "Write error: %s", strerror(rv));
	break;
      }
    }
  }

  free(sys->line);
}

int HandleRead(void *handle) {
  intf_thread_t *intf = (intf_thread_t*)handle;
  intf_sys_t *sys = intf->p_sys;

  static char ch, pch;

  int rv = recv(sys->fd, &ch, 1, 0);
  if(rv == -1)
    return errno;
  else if(rv == 0)
    return -2;
  
  if(pch == '\r' && ch == '\n') { /* were the last two characters \r\n? */
    sys->line[sys->line_loc-1] = '\0'; /* overwrite CR with a nullbyte */
    LineReceived(handle, sys->line);
    sys->line_loc = 0;
    sys->line = (char *)malloc(MAX_LINE * sizeof(char)); /* allocate a new line, lineReceived will free the old one */
  } else {
    sys->line[sys->line_loc] = ch;
    pch = ch;
    sys->line_loc++;
  }

  return 0;
}
Esempio n. 4
0
void MythSystemIOHandler::remove(HANDLE h)
{
    m_pLock.lock();
    if (m_read)
    {
        PMap_t::iterator i;
        i = m_pMap.find(h);
        HandleRead(i.key(), i.value());
    }
    m_pMap.remove(h);
    m_pLock.unlock();
}
Esempio n. 5
0
void MythSystemIOHandler::remove(int fd)
{
    m_pLock.lock();
    if (m_read)
    {
        PMap_t::iterator i;
        i = m_pMap.find(fd);
        if ( i != m_pMap.end() )
            HandleRead(i.key(), i.value());
    }
    m_pMap.remove(fd);
    BuildFDs();
    m_pLock.unlock();
}
Esempio n. 6
0
// 异步写操作完成后write_handler触发
void RWHandler::write_handler(const boost::system::error_code& ec)
{
	if (ec)
	{
		//std::cout << "send" << std::endl;
		HandleError(ec);
	}
	else
	{
		//接受消息(非阻塞)
		HandleRead();
	}

}
Esempio n. 7
0
void MythSystemLegacyIOHandler::run(void)
{
    RunProlog();

    LOG(VB_GENERAL, LOG_INFO, QString("Starting IO manager (%1)")
        .arg(m_read ? "read" : "write"));

    while( run_system )
    {
        {
            QMutexLocker locker(&m_pWaitLock);
            m_pWait.wait(&m_pWaitLock);
        }

        while( run_system )
        {
            usleep(10000); // ~100x per second, for ~3MBps throughput
            m_pLock.lock();
            if( m_pMap.isEmpty() )
            {
                m_pLock.unlock();
                break;
            }

            bool datafound = true;
            m_pLock.unlock();

            while ( datafound && run_system )
            {
                m_pLock.lock();

                datafound = false;
                PMap_t::iterator i, next;
                for( i = m_pMap.begin(); i != m_pMap.end(); i = next )
                {
                    next = i + 1;

                    if( m_read )
                        datafound |= HandleRead(i.key(), i.value());
                    else
                        datafound |= HandleWrite(i.key(), i.value());
                }
                m_pLock.unlock();
            }
        }
    }
    RunEpilog();
}
Esempio n. 8
0
void MythSystemIOHandler::run(void)
{
    threadRegister(QString("SystemIOHandler%1").arg(m_read ? "R" : "W"));
    LOG(VB_GENERAL, LOG_INFO, QString("Starting IO manager (%1)")
        .arg(m_read ? "read" : "write"));

    QMutex mutex;

    while( gCoreContext )
    {
        mutex.lock();
        m_pWait.wait(&mutex);
        mutex.unlock();

        while( gCoreContext )
        {
            usleep(10000); // ~100x per second, for ~3MBps throughput
            m_pLock.lock();
            if( m_pMap.isEmpty() )
            {
                m_pLock.unlock();
                break;
            }
            
            bool datafound = true;
            m_pLock.unlock();

            while ( datafound && gCoreContext )
            {
                m_pLock.lock();

                datafound = false;
                PMap_t::iterator i, next;
                for( i = m_pMap.begin(); i != m_pMap.end(); i = next )
                {
                    next = i + 1;

                    if( m_read )
                        datafound |= HandleRead(i.key(), i.value());
                    else
                        datafound |= HandleWrite(i.key(), i.value());
                }
                m_pLock.unlock();
            }
        }
    }
    threadDeregister();
}
Esempio n. 9
0
BOOL CUdpCast::ProcessNetworkEvent()
{
	BOOL bContinue = TRUE;
	WSANETWORKEVENTS events;
	
	int rc = ::WSAEnumNetworkEvents(m_soClient, m_evSocket, &events);

	if(rc == SOCKET_ERROR)
		bContinue = HandleError(events);

	if(bContinue && events.lNetworkEvents & FD_READ)
		bContinue = HandleRead(events);

	if(bContinue && events.lNetworkEvents & FD_WRITE)
		bContinue = HandleWrite(events);

	if(bContinue && events.lNetworkEvents & FD_CLOSE)
		bContinue = HandleClose(events);

	return bContinue;
}
Esempio n. 10
0
BOOL CTcpClient::ProcessNetworkEvent(SHORT events)
{
	BOOL bContinue = TRUE;

	if(bContinue && events & POLLERR)
		bContinue = HandleClose(events);

	if(bContinue && !IsConnected())
		bContinue = HandleConnect(events);

	if(bContinue && events & POLLIN)
		bContinue = HandleRead(events);

	if(bContinue && events & POLLOUT)
		bContinue = HandleWrite(events);

	if(bContinue && events & _POLL_HUNGUP_EVENTS)
		bContinue = HandleClose(events);

	return bContinue;
}
Esempio n. 11
0
void 
CUdpCommClient::OnWinSockEvent()
{
	WSANETWORKEVENTS wsaEnumWork;

	if (SOCKET_ERROR == WSAEnumNetworkEvents(m_dSock, m_hSockEvent, &wsaEnumWork))
	{
		m_nErrorCode = WSAGetLastError();
		HandleError(OCFCLIENT_ERROR_WINSOCK, m_nErrorCode, 0xFF, 0, NULL);
		return;
	}

	if (wsaEnumWork.lNetworkEvents & FD_WRITE)
	{
		if (0 == wsaEnumWork.iErrorCode[FD_WRITE_BIT])
		{
			HandleWrite();
		}
		else
		{
			m_nErrorCode = wsaEnumWork.iErrorCode[FD_READ_BIT];
			HandleError(OCFCLIENT_ERROR_WINSOCK, m_nErrorCode, 0xFF, 0, NULL);
		}
	}

	if (wsaEnumWork.lNetworkEvents & FD_READ)
	{
		if (0 == wsaEnumWork.iErrorCode[FD_READ_BIT])
		{
			HandleRead();
		}
		else
		{
			m_nErrorCode = wsaEnumWork.iErrorCode[FD_READ_BIT];
			HandleError(OCFCLIENT_ERROR_WINSOCK, m_nErrorCode, 0xFF, 0, NULL);
		}
	}
}
Esempio n. 12
0
void MythSystemIOHandler::run(void)
{
    RunProlog();
    LOG(VB_GENERAL, LOG_INFO, QString("Starting IO manager (%1)")
                .arg(m_read ? "read" : "write"));

    m_pLock.lock();
    BuildFDs();
    m_pLock.unlock();

    while( run_system )
    {
        {
            QMutexLocker locker(&m_pWaitLock);
            m_pWait.wait(&m_pWaitLock);
        }

        while( run_system )
        {
            usleep(10000); // ~100x per second, for ~3MBps throughput
            m_pLock.lock();
            if( m_pMap.isEmpty() )
            {
                m_pLock.unlock();
                break;
            }
            
            timeval tv;
            tv.tv_sec = 0; tv.tv_usec = 0;
          
            int retval;
            fd_set fds = m_fds;

            if( m_read )
                retval = select(m_maxfd+1, &fds, NULL, NULL, &tv);
            else
                retval = select(m_maxfd+1, NULL, &fds, NULL, &tv);

            if( retval == -1 )
                LOG(VB_SYSTEM, LOG_ERR,
                    QString("MythSystemIOHandler: select(%1, %2) failed: %3")
                        .arg(m_maxfd+1).arg(m_read).arg(strerror(errno)));

            else if( retval > 0 )
            {
                PMap_t::iterator i, next;
                for( i = m_pMap.begin(); i != m_pMap.end(); i = next )
                {
                    next = i+1;
                    int fd = i.key();
                    if( FD_ISSET(fd, &fds) )
                    {
                        if( m_read )
                            HandleRead(i.key(), i.value());
                        else
                            HandleWrite(i.key(), i.value());
                    }
                }
            }
            m_pLock.unlock();
        }
    }

    RunEpilog();
}
Esempio n. 13
0
//异步读操作完成后read_handler触发
void RWHandler::read_handler(const boost::system::error_code& ec, boost::shared_ptr<std::vector<char> > str)
{
	if (ec)
	{
		//std::cout << "read" << dataToSendIndex << std::endl;
		if (readCount > 0)
			readCount--;
		else
			HandleError(ec);
		
		return;
	}
	else
	{
		//从接收到的信息中获取请求命令
		char command[30] = { 0 };
		int i;
		for (i = 2; i < 30; i++)
		{
			if ((*str)[i] == '|')
				break;
			command[i - 2] = (*str)[i];
		}
		//客户端请求初始化项目信息
		if (strcmp(&(*str)[2], INIT_APPKEYS_INFO) == 0)
		{
			boost::system::error_code ec;
			string sendStr = ETX + (*str)[1];
			write(m_sock, buffer(sendStr, sendStr.size()), ec);
			Sleep(500);

			sendStr = "";
			GenerateSendData(sendStr, projectConfigureInfoInJson);
			write(m_sock, buffer(sendStr, sendStr.size()), ec);
			std::cout << "ProjectConfigure finish!" << std::endl;
			HandleRead();
		}
		//客户端请求初始化异常数据时调用
		else if (strcmp(command, INIT_CRASH_INFO) == 0)
		{
			readCount--;
			initErrorInfo = true;
			TransferDataToJson(crashInfo, &(*str)[i + 1]);
			dataToSendIndex = 0;
			offSet = 0;

			boost::system::error_code ec;
			string sendStr = ETX + (*str)[1] + "Receive";
			write(m_sock, buffer(sendStr, sendStr.size()), ec);
			Sleep(500);

			HandleWrite();
		}
		//客户端发送获取开发者信息时
		else if (strcmp(&(*str)[2], INIT_DEVELOPER_INFO) == 0)
		{
			readCount--;
			initDeveloper = true;
			GetDeveloperInfo(developerInfo);
			offSet = 0;

			boost::system::error_code ec;
			string sendStr = ETX + (*str)[1] + "Receive";
			write(m_sock, buffer(sendStr, sendStr.size()), ec);
			Sleep(500);

			HandleWrite();
		}
		//收到确认返回时,根据返回执行不同的操作
		else if ((*str)[0] == ETX[0])
		{
			//std::cout << "接收消息:" << &(*str)[0] << std::endl;
			//收到返回,设置重发为false
			isReSend = false;
			if (initErrorInfo)
			{
				//int sendId = (*str)[1] - '0';
				if ((offSet + OFFSET) > crashInfo[dataToSendIndex].size())
				{
					std::cout << dataToSendIndex << "发送完成!" << std::endl;
					++dataToSendIndex;
					//判断是否还有下一条异常,如果有则继续发送,无则关闭连接
					if (dataToSendIndex < crashInfo.size())
					{
						offSet = 0;
						HandleWrite();
					}
					else
					{
						boost::system::error_code ec;
						string sendStr;
						GenerateSendData(sendStr, "SendFinish");
						write(m_sock, buffer(sendStr, sendStr.size()), ec);
						initErrorInfo = false;
					}
				}
				else
				{
					offSet = offSet + OFFSET;
					HandleWrite();
				}
			}
			else if (initDeveloper)
			{
				//int sendId = (*str)[1] - '0';
				if ((offSet + OFFSET) > developerInfo.size())
				{
					std::cout << "开发者信息发送完成!" << std::endl;
					boost::system::error_code ec;
					string sendStr;
					GenerateSendData(sendStr, "SendFinish");
					write(m_sock, buffer(sendStr, sendStr.size()), ec);
					initDeveloper = false;
				}
				else
				{
					offSet = offSet + OFFSET;
					HandleWrite();
				}
			}
			HandleRead();
		}
		//客户端返回更新内容,如分配给哪个用户,异常是否已解决时调用
		else if(strcmp(command, UPDATE_CRASH_INFO) == 0)
		{
			std::cout << "接收消息:" << &(*str)[0] << std::endl;
			UpdateDatabase(&(*str)[i + 1]);
			boost::system::error_code ec;
			string sendStr = ETX + (*str)[1];
			write(m_sock, buffer(sendStr, sendStr.size()), ec);
			readCount++;
			HandleRead();
		}
		//其他情况
		else
		{
			std::cout << "接收消息:" << &(*str)[0] << std::endl;
			HandleRead();
		}
	}
}
Esempio n. 14
0
int TcpManager::RunProcess(int handleSocketCount)
{
    LOG_INFO  <<"TcpManager:: RunProcess start! thread id = "<<  this_thread::get_id();
    int ret = 0;

    epoll_event* event_buf =NULL;
    event_buf  = new epoll_event[handleSocketCount];
    if(event_buf == NULL)
    {
        return -1;
    }



    epoll_event listen_ev;
    listen_ev.data.fd  =m_listenSocket.m_socket;
    listen_ev.events=EPOLLIN;

    if(epoll_ctl(m_epoll,EPOLL_CTL_ADD,m_listenSocket.m_socket,&listen_ev) <0)
    {
        LOG_INFO<<"epoll_error";
        return ret = -1;
    }

    int event_count = 0;
    m_bRunning = true;
    while(m_bRunning)
    {
        event_count  =epoll_wait(m_epoll,event_buf,handleSocketCount, 500);
        if(event_count >0)
        {
            for(int i = 0 ; i<event_count ; i++)
            {
                if( event_buf[i].data.fd  == m_listenSocket.m_socket)
                {
                    HandleAccept();
                }
                else if(event_buf[i].events&EPOLLIN)
                {
                    HandleRead(event_buf[i].data.fd);
                }
                else if(event_buf[i].events&EPOLLOUT)
                {
                    HandleWrite(event_buf[i].data.fd);
                }
                else
                {
                    LOG_INFO<< "epoll wait ";
                    CloseSocket(event_buf[i].data.fd);
                    //错误或者对方关闭
                }
            }

        }
        else if(event_count == 0) //超时
        {

            //LOG_EVERY_N(INFO, 10) << "epoll timteout";
            //超时
        }
        else  //error
        {
            if(errno == EINTR){
                continue;
            }else
            {
                 LOG_INFO<< "epoll erorr errno="<<errno;
            }

        }
    }//while

    LOG_INFO  <<"TcpManager:: RunProcess end! thread id = "<<  this_thread::get_id();
    return 0;
}