Example #1
0
void Acceptor::handleEvent(int events)
{
  std::cout << "acceptor::events" << std::endl;
  assert(events && EPOLLIN);  //we should make sure the events is epollin
  while(true)
  {
    Socket* newsock = m_socket->accept();
    std::cout << "newsock:" << newsock << std::endl;
    if( newsock == NULL ){
      if( errno == EINTR ) continue;
      else if( errno == EWOULDBLOCK 
            || errno == EAGAIN ){
        return;
      }else{
        // should not execute here.
        // TODO: log error
        assert(false);
        return;
      }
    }else{
      m_connlist.push_back(newsock);
      newsock->setNonBlock();
      EventLoop* loop = getNextLoop();      
      Client* client = new Client(newsock, loop);
      loop->registerHandle(client, EPOLLIN|EPOLLERR);
      return;
    }
  }
}
Example #2
0
int main(int argc, char* argv[])
{
#ifdef WIN32
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;
    wVersionRequested = MAKEWORD(2, 2);
    err = WSAStartup(wVersionRequested, &wsaData);
#endif

    int numThreads = 0;

    if(argc > 1)
    {
        benchmark = true;
        //Logger::setLogLevel(Logger::WARN);
        numThreads = atoi(argv[1]);
    }

    MuduoPlus::LogPrinter = LogPrint;

    EventLoop loop;
    HttpServer server(&loop, InetAddress("0.0.0.0", 8000), "dummy");
    server.setHttpCallback(onRequest);
    server.setThreadNum(numThreads);
    server.start();
    loop.loop();
}
Example #3
0
int main()
{
    EventLoop loop;
    TcpServer s(&loop,true,8001);
    s.start();
    loop.loop();
}
int main(int argc, char* argv[])
{
    int fd = timerfd_create(CLOCK_MONOTONIC,TFD_NONBLOCK | TFD_CLOEXEC);

    ChannelPtr channel(new Channel(fd));
    channel->setChannel2Read();
    channel->setReadCallback(func);

    EventLoop loop;
    loop.updateChannel(channel);

    elp = &loop;

    struct itimerspec howlog;

    bzero(&howlog, sizeof(howlog));

    howlog.it_value.tv_sec = 5;

    timerfd_settime(fd,0,&howlog,NULL);

    cout << "begin" <<endl;

    loop.Start();

    close(fd);

    return 0;
}
Example #5
0
void jni_init()
{
    try {
        net_thread = std::thread([] {
            if (!main_loop.init()) {
                return;
            }

            JNIEnv *env;
            bool attached = false;
            int status = java_vm->GetEnv((void **)&env, JNI_VERSION_1_4);
            if (status < 0) {
                LOGE("callback_handler: failed to get JNI environment, assuming native thread");
                status = java_vm->AttachCurrentThread(&env, NULL);
                if (status < 0) {
                    LOGE("callback_handler: failed to attach current thread");
                }
                attached = true;
            }

            main_loop.loop();

            if (attached) {
                java_vm->DetachCurrentThread();
            }
        });
    }
    catch (...) {

    }
}
Example #6
0
void ScriptDebugServer::pauseIfNeeded(JSGlobalObject* dynamicGlobalObject)
{
    if (m_paused)
        return;
 
    if (!getListenersForGlobalObject(dynamicGlobalObject))
        return;

    bool pauseNow = m_pauseOnNextStatement;
    pauseNow |= (m_pauseOnCallFrame == m_currentCallFrame);
    pauseNow |= hasBreakpoint(m_currentCallFrame->sourceID(), m_currentCallFrame->position());
    if (!pauseNow)
        return;

    m_pauseOnCallFrame = 0;
    m_pauseOnNextStatement = false;
    m_paused = true;

    dispatchFunctionToListeners(&ScriptDebugServer::dispatchDidPause, dynamicGlobalObject);
    didPause(dynamicGlobalObject);

    TimerBase::fireTimersInNestedEventLoop();

    EventLoop loop;
    m_doneProcessingDebuggerEvents = false;
    while (!m_doneProcessingDebuggerEvents && !loop.ended())
        loop.cycle();

    didContinue(dynamicGlobalObject);
    dispatchFunctionToListeners(&ScriptDebugServer::dispatchDidContinue, dynamicGlobalObject);

    m_paused = false;
}
Example #7
0
    void TcpServer::newConnection(int sockfd, const InetAddress& peerAddr)
    {
        loop_->assertInLoopThread();
        EventLoop* ioLoop = threadPool_->getNextLoop();
        char buf[64];
        snprintf(buf, sizeof buf, "-%s#%d", ipPort_.c_str(), nextConnId_);
        ++nextConnId_;
        std::string connName = name_ + buf;

        LOG_PRINT(LogType_Info, "TcpServer::newConnection [%s] - new connection [%s] from %s",
                  name_.c_str(), connName.c_str(), peerAddr.toIpPort().c_str());
        InetAddress localAddr(SocketOps::getLocalAddr(sockfd));
        // FIXME poll with zero timeout to double confirm the new connection
        // FIXME use make_shared if necessary
        TcpConnectionPtr conn(new TcpConnection(ioLoop,
                                                connName,
                                                sockfd,
                                                localAddr,
                                                peerAddr));
        connections_[connName] = conn;
        conn->setConnectionCallback(connectionCallback_);
        conn->setMessageCallback(messageCallback_);
        conn->setWriteCompleteCallback(writeCompleteCallback_);
        conn->setCloseCallback(
            std::bind(&TcpServer::removeConnection, this, std::placeholders::_1)); // FIXME: unsafe
        ioLoop->runInLoop(std::bind(&TcpConnection::connectEstablished, conn));
    }
VOD_SessionControl::~VOD_SessionControl()
{
    LOG(DLOGL_REALLY_NOISY, " destruct mVodSessionId: %d ", mVodSessionId);

    pthread_mutex_lock(&mVodSessionListMutex);


    mActiveVodSessionMap.erase(mVodSessionId);


    LOG(DLOGL_REALLY_NOISY, "sendMsgInfoList.size(): %d", sendMsgInfoList.size());

    EventLoop* evtLoop = ptrOnDemand->GetEventLoop();

    // Remove all event timers and messages from send list
    if (!sendMsgInfoList.empty())
    {
        list<SendMsgInfo *>::iterator itr;
        itr = sendMsgInfoList.begin();
        while (itr != sendMsgInfoList.end())
        {
            EventTimer *evt = (*itr)->evtTimer;
            LOG(DLOGL_REALLY_NOISY, "evtLoop->delTimer: %p", evt);
            if (evtLoop)
            {
                evtLoop->delTimer(evt);
            }
            delete *itr;
            itr = sendMsgInfoList.erase(itr);
        }
    }

    pthread_mutex_unlock(&mVodSessionListMutex);
    LOG(DLOGL_REALLY_NOISY, "exit");
}
int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        printf("Usage : %s <server_port>\n", argv[0]);
        return 0;
    }

    EventLoop loop;
    InetAddress serverAddr("127.0.0.1", atoi(argv[1]));

    const static int flag = 2;
    if (flag == 1)
    {
        TcpClient client(&loop, serverAddr);
        client.enableRetry();
        client.setConnectionCallback(test_client::clientConnectionCallback);
        client.setMessageCallback(test_client::clientMessageCallback);
        client.connect();
        loop.addTimer(test_client::sendDataByClient, 1, true);   //启动一个每1s运行一次的定时器
        loop.loop();
    }
    else if (flag == 2)
    {
        test_client_stdin::TestTcpClient client(&loop, serverAddr);
        client.connect();
        loop.loop();
    }
}
int main(int argc, char **argv)
{
  plan_tests(1);

  ScreenGlobalInit screen;

#ifdef ANDROID
  TopWindow main_window;
  EventLoop loop(*event_queue, main_window);
  Event event;
#elif defined(ENABLE_SDL)
  TopWindow main_window;
  EventLoop loop(main_window);
  SDL_Event event;
#else
  EventLoop loop;
  MSG event;
#endif

  TestNotify notify;
  TestThread thread(notify);
  thread.Start();

#ifndef USE_GDI
  while (!quit && loop.get(event))
    loop.dispatch(event);
#else
  while (!quit && loop.get(event))
    loop.dispatch(event);
#endif

  ok1(quit);

  return exit_status();
}
Example #11
0
int main(int argc, char* argv[])
{
	uint16_t port = 9981;
	if (argc > 1 )
	{
		port = static_cast<uint16_t>(atoi(argv[1]));
	}

	LOG_INFO << "pid=" << getpid() << ",tid=" << CurrentThread::tid();
	InetAddress listenAddr(port);

	EventLoop loop;
	g_eventLoop = &loop;

	TcpServer server(&loop, listenAddr, "socks4");

	server.setConnectionCallback(onServerConnection);
	server.setMessageCallback(onServerMessage);

	server.start();

	loop.loop();

	 
}
Example #12
0
int main(int argc, const char *argv[])
{
    EventLoop loop;
    g_loop = &loop;
    loop.runAfter(30.0, boost::bind(&EventLoop::quit, &loop));
    curl::Curl::initialize(curl::Curl::kCURLssl);
    curl::Curl curl(&loop);

    curl::RequestPtr req = curl.getUrl("http://chenshuo.com");
    req->setDataCallback(onData);
    req->setDoneCallback(done);
    
    //curl::RequestPtr req2 = curl.getUrl("http://github.com");
    // req2->allowRedirect(5);
    //req2->setDataCallback(onData);
    //req2->setDoneCallback(done);
    
    //curl::RequestPtr req3 = curl.getUrl("http://example.com");
    // req3->allowRedirect(5);
    //req3->setDataCallback(onData);
    //req3->setDoneCallback(done2);

    loop.loop();
    return 0;
}
Example #13
0
// static methods
int BaseConn::SendPkt(net_handle_t handle, PktBase* pkt)
{
    EventLoop* el = get_io_event_loop(handle);
    PendingEventMgr* event_mgr = g_pending_event_mgr.GetIOResource(handle);
    
    if (el->IsInLoopThread()) {
        ConnMap_t::iterator it_conn = event_mgr->conn_map.find(handle);
        if (it_conn != event_mgr->conn_map.end()) {
            BaseConn* conn = it_conn->second;
            if (conn->IsOpen()) {
                conn->SendPkt(pkt);
                delete pkt;
            } else {
                conn->AddToWaitPktList(pkt);
            }
        } else {
            delete pkt;
        }
    } else {
        event_mgr->mutex.Lock();
        event_mgr->pkt_list.push_back(make_pair(handle, pkt));
        event_mgr->mutex.Unlock();
        
        el->Wakeup();
    }
    
    return 0;
}
Example #14
0
int main(int argc, char *argv[])
{
    if(argc != 7)
    {
        fprintf(stderr, "Usage: %s <host_ip> <port> <threads> <blocksize> <clients> <time>\n", argv[0]);
        fprintf(stderr, "for example : %s 0.0.0.0 8888 10 100 1000 5. It means that:\n", argv[0]);
        fprintf(stderr, "\tserver address is 0.0.0.0:8888, and\n");
        fprintf(stderr, "\tcreate 10 threads, message size is 100 Byte, create 1000 clients, and run 5 seconds\n");
    }
    else
    {
        LOG_SET_PRIORITY(zl::base::ZL_LOG_PRIO_WARNING);

        const char *ip = argv[1];
        uint16_t port = static_cast<uint16_t>(atoi(argv[2]));
        int threadCount = atoi(argv[3]);
        int blockSize = atoi(argv[4]);
        int sessionCount = atoi(argv[5]);
        int timeout = atoi(argv[6]);

        EventLoop loop;
        InetAddress serverAddr(ip, port);

        Client client(&loop, serverAddr, blockSize, sessionCount, timeout, threadCount);
        loop.loop();
    }
}
Example #15
0
std::shared_ptr<TcpClient>
EventLoopGroup::creatTcpClient(const std::string &host,
                               const std::string &service) {
    std::shared_ptr<TcpClient> tcpClient = std::make_shared<TcpClient>();
    std::weak_ptr<TcpClient> weakTcpClient = tcpClient;

    Resolver::async_resolve(
        host, service, [this, weakTcpClient](std::list<Endpoint> eps) {
            if (weakTcpClient.expired() || eps.empty())
                return;

            auto tcpClient = weakTcpClient.lock();
            SockPtr sockPtr = std::make_shared<Socket>(eps.front());
            sockPtr->connect();

            EventLoop *loop = robinLoop1(sockPtr->fd());

            tcpClient->setEventLoop(loop);
            tcpClient->setSocket(sockPtr);

            // BUG tcpClient与当前线程不在一个线程上时,可能会引起内存错误
            //            tcpClient->start();
            // FIX
            if (loop == EventLoop::curr_thread_loop()) {
                tcpClient->start();
            } else {
                loop->runEventHandler([tcpClient] { tcpClient->start(); });
            }
        });
    return tcpClient;
}
void JavaScriptDebugServer::pauseIfNeeded(Page* page)
{
    if (m_paused)
        return;

    if (!page || !hasListenersInterestedInPage(page))
        return;

    bool pauseNow = m_pauseOnNextStatement;
    pauseNow |= (m_pauseOnCallFrame == m_currentCallFrame);
    pauseNow |= (m_currentCallFrame->line() > 0 && hasBreakpoint(m_currentCallFrame->sourceIdentifier(), m_currentCallFrame->line()));
    if (!pauseNow)
        return;

    m_pauseOnCallFrame = 0;
    m_pauseOnNextStatement = false;
    m_paused = true;

    dispatchFunctionToListeners(&JavaScriptDebugListener::didPause, page);

    setJavaScriptPaused(page->group(), true);

    TimerBase::fireTimersInNestedEventLoop();

    EventLoop loop;
    m_doneProcessingDebuggerEvents = false;
    while (!m_doneProcessingDebuggerEvents && !loop.ended())
        loop.cycle();

    setJavaScriptPaused(page->group(), false);

    m_paused = false;
}
int main(int argc, char** argv)
{
    EventLoop mainLoop;

    ssdb = std::make_shared<SSDBMultiClient>();
    ssdb->startNetThread([&](){
        mainLoop.wakeup();
    });

    ssdb->addProxyConnection(argv[1], atoi(argv[2]));

    ssdb->redisGet("hello", [](const std::string& value, const Status& status){
        cout << value << endl;
    });

    for (size_t i = 0; i < 1000; i++)
    {
        ssdb->redisGet("hello", async_get_callback);
    }

    ssdb->qpush("mlist", "a", nullptr);

    while (true)
    {
        mainLoop.loop(1);
        ssdb->pull();
        ssdb->forceSyncRequest();
    }
}
Example #18
0
EventLoop::~EventLoop() {
	uv_ref((uv_handle_t*) &deleteObjectsHandle);
	uv_prepare_stop(&deleteObjectsHandle);
	uv_close((uv_handle_t*) &deleteObjectsHandle, nullptr);

	// Wait remaining handle to close
	uv_run(&loop, UV_RUN_DEFAULT);

	if(uv_loop_alive(&loop)) {
		log(LL_Warning, "Loop still used but delete requested, handles:\n");
		uv_walk(&loop,
		        [](uv_handle_t* handle, void* arg) {
			        EventLoop* self = (EventLoop*) arg;
			        const char* type;
			        switch(handle->type) {
#define X(uc, lc) \
	case UV_##uc: \
		type = #lc; \
		break;
				        UV_HANDLE_TYPE_MAP(X)
#undef X
				        default:
					        type = "<unknown>";
			        }

			        self->log(LL_Warning, "  [%08X] %s %p\n", handle->flags, type, handle);
		        },
		        this);
void VOD_SessionControl::RemoveMessageFromSendList(SendMsgInfo *msgInfo)
{
    pthread_mutex_lock(&mVodSessionListMutex);
    LOG(DLOGL_REALLY_NOISY, "RemoveMessageFromSendList sendMsgInfoList.size(): %d", sendMsgInfoList.size());

    if (!sendMsgInfoList.empty())
    {
        list<SendMsgInfo *>::iterator itr;
        for (itr = sendMsgInfoList.begin(); itr != sendMsgInfoList.end(); ++itr)
        {
            if ((*itr)->transId == msgInfo->transId)
            {
                EventLoop* evtLoop = ptrOnDemand->GetEventLoop();
                if (evtLoop)
                {
                    evtLoop->delTimer((*itr)->evtTimer);
                }
                LOG(DLOGL_REALLY_NOISY, "deleting Message with address: %p", *itr);
                delete *itr;
                *itr = NULL;

                sendMsgInfoList.erase(itr);
                break;
            }
        }
    }

    pthread_mutex_unlock(&mVodSessionListMutex);
}
Example #20
0
int main(int argc, char **argv)
{
    logging::Init(argv[0], "../../log/log_");

    LOG_INFO << "this thread's tid = " << this_thread::get_id();

#ifdef WIN32    //windows
    if(sockets::SocketStartUp() != 0){  
        LOG_SOCKET_FATAL << "Ì×½Ó×Ö³õʼ»¯Ê§°Ü!";
        return -1;
    }
#endif

    const int port = 23;

    EventLoop loop;
    InetAddress listenAddr(port);
    InetAddress peerAddr("127.0.0.1", port);

    BaseSvr basesvr(&loop, listenAddr);
    basesvr.Start();
    basesvr.ConnectToPeer(peerAddr);
    basesvr.ConnectToDB("tcp://127.0.0.1:3306", "root", "123456", "svr", 5);

    loop.loop();

    system("pause");
}
Example #21
0
int main(int argc, char *argv[]) {

  // Usage : MiniHttpd has two ways to initialize
  // (1) simple way, just need one line of code like below
  //     But please remeber that in this way, 
  //     program will be aborted if @port bind failed. Be care!!!!
  //
  // ::argus::common::MiniHttpd httpserver(&loop, port);
  //
  // (2) Second way is divided into two steps.
  //     firstly construct a MiniHttpd instance named httpserver;
  //     Secondly call httpserver.bind(port);
  //     bind() will fail and return false when @port already in use
  //
  // ::argus::common::MiniHttpd httpserver(&loop);
  // bool success = httpserver.bind(port);
  // if (!success) {
  //     LOG(ERROR) << "port bind failed";
  //     return EXIT_FAIURE;
  // }
  //
  EventLoop loop;
  MiniHttpd httpd(&loop, 8889);

  httpd.enableLogging(false);
  httpd.enableIpFilter(true);

  bool succ = httpd.setCallBack("hellocb", callbackOne);
  assert(succ);

  int ret = loop.loop();
  LOG(INFO) << "EventLoop::loop() returns " << ret;
}
Example #22
0
	void EventLoop::callback_activity(android_app* pApplication, int32_t pCommand)
	{
		Pegas_log_info_loop("EventLoop::callback_activity [pApplication: %X, pCommand: %d]", pApplication, pCommand);

		EventLoop* pInstance = (EventLoop*)pApplication->userData;
		pInstance->processActivityEvent(pCommand);
	}
Example #23
0
int main()
{
    EventLoop loop;
    TcpServer server(&loop, InetAddress(1079), "Finger");
    server.setMessageCallback(onMessage);
    server.start();
    loop.loop();
}
Example #24
0
	void EventLoop::PrepareHandle(uv_prepare_t *handle, int status)
	{
		EventLoop *eventloop = static_cast<EventLoop *>(handle->data);
		QGuiApplication *app = eventloop->GetApp();

//		if (app->hasPendingEvents())
//			app->processEvents();
	}
void PageScriptDebugServer::runEventLoopWhilePausedInternal()
{
    TimerBase::fireTimersInNestedEventLoop();

    EventLoop loop;
    while (!m_doneProcessingDebuggerEvents && !loop.ended())
        loop.cycle();
}
Example #26
0
int main()
{
	EventLoop loop;
	TestServer server(&loop, "testserver", "127.0.0.1", 5555);
	server.start();
	loop.loop();
	return 0;
}
Example #27
0
int main()
{
    EventLoop loop;
    InetAddress proxyAddr("127.0.0.1", 6001);
    dbdky::cma_client::cma_client client(&loop, proxyAddr, "cma_client");
    client.setGetSendDataCallback(boost::bind(getTestData, _1));
    client.start();
    loop.loop();
}
    void test()
    {
        printf("main(): pid = %d, tid = %d\n", getpid(), this_thread::get_id().value());
        EventLoop loop;
        Thread t(threadFunc);

        loop.loop();
        t.join();
    }
Example #29
0
int main()
{
	EventLoop el;
	InetAddress ia("127.0.0.1", 9527);
	TcpServer ts(&el, ia, "TcpServerTest", ServerOption_t::eReusePort);
	ts.Start();
	el.Loop();
	return 0;
}
Example #30
0
void runServer(uint16_t port)
{
	EventLoop loop;
  TcpServer server(&loop, InetAddress(port), "ClockServer");
  server.setConnectionCallback(serverConnectionCallback);
  server.setMessageCallback(serverMessageCallback);
  server.start();
  loop.loop();
}