//等待10s,如果没收到返回,即isReSend为true则调用重发
void RWHandler::wait_handler()
{	
	try
	{
		if (isDisConnected)
			return;

		if (m_timer.expires_at() <= deadline_timer::traits_type::now() && isReSend)
		{
			if (m_sock.is_open())
			{
				std::cout << "没有接收到返回,重发消息!" << std::endl;
				HandleWrite();
			}
			else
				std::cout << "重发失败,连接已断开!" << std::endl;
		}
		m_timer.async_wait(boost::bind(&RWHandler::wait_handler, this));
	}
	catch (boost::system::error_code ec)
	{
		std::cout << "WaitError" << std::endl;
		return;
	}
	
}
Beispiel #2
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;
}
Beispiel #3
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();
}
Beispiel #4
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();
}
Beispiel #5
0
BOOL 
CUdpCommClient::Do()
{
	DWORD dwIdx;
	HANDLE awsaEvent[3];

	//
	awsaEvent[0] = m_hSockEvent;
	awsaEvent[1] = m_hWrEvent;
	awsaEvent[2] = m_hQuit;

	//
	while (FALSE == CThreadClient::IsEnd())
	{
		dwIdx = ::WaitForMultipleObjects(3, awsaEvent, FALSE, m_dwIdleTime);

		switch (dwIdx)
		{
			case WAIT_OBJECT_0:
				OnWinSockEvent();
				break;

			case (WAIT_OBJECT_0 + 1):
				HandleWrite();
				break;

			case (WAIT_OBJECT_0 + 2):
				break;

			case WAIT_TIMEOUT:
				IdleWrite();
				break;
		}

		//
		if (0 < m_tSessionTimeout && difftime(time(NULL), m_tTimeout) > m_tSessionTimeout)
		{
			m_tTimeout = time(NULL);
			HandleIdle();
		}
	}

	return TRUE;
}
Beispiel #6
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;
}
Beispiel #7
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;
}
Beispiel #8
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);
		}
	}
}
Beispiel #9
0
void
User::SendPacket(::BoostAsioNetwork::Packet * pPacket)
{
	HandleWrite(pPacket);
}
Beispiel #10
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();
}
Beispiel #11
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();
		}
	}
}
Beispiel #12
0
void HandleRequest() {
    char* token;
    short keep_processing = 1;
    int offset;

    DebugPrint("Received request %s" _C_ recv_buffer);
    token = FirstToken();
    while (token != 0 && keep_processing) {
        switch (to_request(token)) {
            case ACTIVITY:
                HandleActivity();
                break;
            case COMMAND: // COMMAND
                HandleCommand();
                break;
            case EXIT: // EXIT
                HandleQuit();
                break;
            case GET: // GET
                HandleGet();
                break;
            case KILL:
                HandleKill();
                break;
            case LISPGET: // LISPGET {STATE | GAMEINFO | MAPINFO}
                HandleLispGet();
                break;
            case MAP: // Load new map
                if (HandleNewMap()) {
                    LastPausedCycle = 0;
                    keep_processing = 0;
                }
                break;
            case PING: // PING
                HandlePing();
                break;
            case QUIT: // QUIT
                HandleQuit();
                break;
            case RESTART: // RESTART / RESET
                HandleRestart();
                LastPausedCycle = 0;
                keep_processing = 0;
                break;
            case SPEED: // SPEED
                HandleSpeed();
                break;
            case TRANSITION: // TRANSITION
                HandleTransition();
                keep_processing = 0;
                break;
            case VIDEO: // VIDEO
                HandleVideo();
                break;
            case WRITE:
                HandleWrite();
                break;
            case CYCLE:
                HandleGetCycle();
                break;
            case Z:
                HandleRandomSeed();
                break;
            default:
                SendResponseMessage("Unknown command.\n", 3);
        }
        token = NextToken();
    }

    // Bring pending commands to the front of recv_buffer
    if (token != 0) {
        offset = token + strlen(token) - temp_buffer;
        temp_buffer[offset] = recv_buffer[offset];
        strcpy(recv_buffer, token);
    } else
        memset(recv_buffer, 0, RECV_BUFFER_SIZE); // Clear the command buffer
}
Beispiel #13
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;
}