示例#1
0
文件: log_file.cpp 项目: coneo/walle
void LogFile::roll()
{
    m_curFilename = getFileNameBynow();
    load();

    m_logHour = timeNow().tm_hour;
}
示例#2
0
文件: log_file.cpp 项目: coneo/walle
void LogFile::append(const char* msg, const size_t len)
{
    if (m_logHour != timeNow().tm_hour)
        roll();

    ssize_t n = writeto(msg, len);
    if (-1 == n)
    {
        printf("append log file failed\n");
        printf("Error no is: %d\n", errno);
        printf("Error description is:%s\n", strerror(errno));
        return ;
    }
    size_t rest = len - n;
    while (rest)
    {
        ssize_t rt = writeto(msg + n, rest);
        if (-1 == rt)
        {
            printf("append log file failed\n");
            printf("Error no is: %d\n", errno);
            printf("Error description is:%s\n", strerror(errno));
            break;
        }
        rest -= rt;
    }
}
示例#3
0
文件: log_file.cpp 项目: coneo/walle
std::string LogFile::getFileNameBynow()
{
    struct tm vtm = timeNow();
    char t_time[32];
    snprintf(t_time, sizeof(t_time), ".%4d%02d%02d-%02d", vtm.tm_year+1990, vtm.tm_mon+1, vtm.tm_mday, vtm.tm_hour);
    return m_filename + t_time;
}
示例#4
0
文件: bot.cpp 项目: heihachi/IRC-Bot
bool IrcBot::sendPong(char *buf)
{
    // get reply address
    // loop through bug and find location of PING
    // search through each char in toSearch

    char * toSearch = "PING";

    for(int i = 0;i<strlen(buf);i++)
    {
        if(buf[i] == toSearch[0])
        {
            bool found = true;
            for(int x = 1;x<4;x++)
            {
                if(buf[i+x] != toSearch[x])
                    found = false;
            }
            // if found return true
            if(found == true)
            {
                int count = 0;
                //Count the chars
                for (int x = (i+strlen(toSearch)); x < strlen(buf);x++)
                {
                    count++;
                }

                //Create the new char array
                char returnHost[count + 5];
                returnHost[0]='P';
                returnHost[1]='O';
                returnHost[2]='N';
                returnHost[3]='G';
                returnHost[4]=' ';

                count = 0;
                //set the hostname data
                for (int x = (i+strlen(toSearch)); x < strlen(buf);x++)
                {
                    returnHost[count+5]=buf[x];
                    count++;
                }

                //send the pong
                //if (sendData(returnHost))
                if(sendCommand(ConnectSocket, "%s\r\n", returnHost))
                {
                    cout << "Sent ping pong ~~ " << timeNow() << endl;
                }
                return true;
            }
        }
    }
}
示例#5
0
/* DON'T MODIFY */
MYBOOL BFP_CALLMODEL bfp_mustrefactorize(lprec *lp)
{
    MYBOOL test = lp->is_action(lp->spx_action, ACTION_REINVERT | ACTION_TIMEDREINVERT);
    if(!test) {
        REAL   f;
        INVrec *lu = lp->invB;

        if(lu->num_pivots > 0)
            f = (timeNow()-lu->time_refactstart) / (REAL) lu->num_pivots;
        else
            f = 0;

        /* Always refactorize if we are above the set pivot limit */
        if(lu->force_refact ||
                (lu->num_pivots >= lp->bfp_pivotmax(lp)))
            lp->set_action(&lp->spx_action, ACTION_REINVERT);

        /* Check if we should do an optimal time-based refactorization */
        else if(lu->timed_refact && (lu->num_pivots > 1) &&
                (f > MIN_TIMEPIVOT) && (f > lu->time_refactnext)) {
            /* If we have excessive time usage in automatic mode then
               treat as untimed case and update optimal time metric, ... */
            if((lu->timed_refact == AUTOMATIC) &&
                    (lu->num_pivots < 0.4*lp->bfp_pivotmax(lp)))
                lu->time_refactnext = f;
            /* ... otherwise set flag for the optimal time-based refactorization */
            else
                lp->set_action(&lp->spx_action, ACTION_TIMEDREINVERT);
        }

        /* Otherwise simply update the optimal time metric */
        else
            lu->time_refactnext = f;
#if 0
        if(lu->num_pivots % 10 == 0)
            lp->report(lp, NORMAL, "bfp pivot %d - start %f - timestat %f",
                       lu->num_pivots, lu->time_refactstart, f);
#endif
    }

    test = lp->is_action(lp->spx_action, ACTION_REINVERT | ACTION_TIMEDREINVERT);
    return(test);
}
示例#6
0
void BFP_CALLMODEL bfp_updaterefactstats(lprec *lp)
{
    INVrec *lu = lp->invB;

    /* Signal that we are refactorizing */
    lu->is_dirty = AUTOMATIC;

    /* Set time of start of current refactorization cycle */
    lu->time_refactstart = timeNow();
    lu->time_refactnext  = 0;
    lu->user_colcount = 0;

    /* Do the numbers */
    if(lu->force_refact)
        lu->num_dense_refact++;
    else if(lu->timed_refact && lp->is_action(lp->spx_action, ACTION_TIMEDREINVERT))
        lu->num_timed_refact++;
    lu->num_refact++;
}
示例#7
0
//
// Class methods
//
void cItem::archive()
{
	std::string saveFileName( SrvParms->savePath + SrvParms->itemWorldfile + SrvParms->worldfileExtension );
	std::string timeNow( getNoXDate() );
	for( int i = timeNow.length() - 1; i >= 0; --i )
		switch( timeNow[i] )
		{
			case '/' :
			case ' ' :
			case ':' :
				timeNow[i]= '-';
		}
	std::string archiveFileName( SrvParms->archivePath + SrvParms->itemWorldfile + timeNow + SrvParms->worldfileExtension );


	if( rename( saveFileName.c_str(), archiveFileName.c_str() ) != 0 )
	{
		LogWarning("Could not rename/move file '%s' to '%s'\n", saveFileName.c_str(), archiveFileName.c_str() );
	}
	else
	{
		InfoOut("Renamed/moved file '%s' to '%s'\n", saveFileName.c_str(), archiveFileName.c_str() );
	}
}
示例#8
0
int main(int argc, char *argv[]) {
  opterr = 0;

  int width = -1;
  int height = -1;
  int max_frames = -1;
  const char *in = NULL;
  const char *out = NULL;
  bool time = false;
  int stripType = Blend::STRIP_TYPE_THIN;

  const struct option long_options[] = {
    {"width",  required_argument, 0, 'w'},
    {"height", required_argument, 0, 'h'},
    {"in",     required_argument, 0, 'i'},
    {"out",    required_argument, 0, 'o'},
    {"strip",  required_argument, 0, 's'},
    {"max",    required_argument, 0, 'm'},
    {"time",   no_argument      , 0, 't'},
    {0,        0,                 0, 0}
  };

  int c;

  if (argc == 1) {
    usage();
    return 0;
  }

  while (1) {
    c = getopt_long(argc, argv, "w:h:i:o:s:m:t", long_options, NULL);
    if (c == -1) {
      break;
    }

    switch (c) {
    case 'w':
      width = atoi(optarg);
      break;

    case 'h':
      height = atoi(optarg);
      break;

    case 'i':
      in = optarg;
      break;

    case 'o':
      out = optarg;
      break;

    case 't':
      time = true;
      break;

    case 's':
      stripType = atoi(optarg);
      break;

    case 'm':
      max_frames = atoi(optarg);
      break;

    case '?':
      usage();
      return 0;
    }
  }

  // validate
  if (width <= 0) {
    std::cerr << "invalid width " << width << std::endl;
    return 1;
  }

  if (height <= 0) {
    std::cerr << "invalid height " << height << std::endl;
    return 1;
  }

  if (!in) {
    std::cerr << "input file not provided" << std::endl;
    return 1;
  }

  if (!out) {
    std::cerr << "output file not provided" << std::endl;
    return 1;
  }

  if (stripType < 0 || stripType > 1) {
    std::cerr << "invalid strip type " << stripType << std::endl;
    return 1;
  }

  // input
  int fd = open(in, O_RDONLY);
  if (fd == -1) {
    perror("open");
    return 1;
  }


  int size = (width * height * 12) / 8;

  std::cout << "input width = " << width << ", height = " << height << std::endl;
  std::cout << "strip type: " << stripType << " (" << strips[stripType] << ")" << std::endl;

  int frames = count_frames(fd, size);

  if (frames == -1) {
    close(fd);
    return 1;
  }

  if (max_frames > 0) {
    frames = MIN(frames, max_frames);
  }

  // initialize our mosaicer
  Mosaic m;
  if (!m.initialize(blendingType, stripType, width, height, frames, true, 5.0f)) {
    std::cerr << "Failed to initialize mosaicer" << std::endl;
    close(fd);
    return 1;
  }

  std::vector<int> times;
  std::vector<unsigned char *> mosaic_frames;
  unsigned char *in_data = NULL;

  for (int x = 0; x < frames; x++) {
    // allocate:
    if (!in_data) {
      in_data = new unsigned char[size];
    }

    if (read(fd, in_data, size) == size) {
      // process
      int time = timeNow();
      int ret = m.addFrame(in_data);
      time = timeNow() - time;

      times.push_back(time);

      if (ret == Mosaic::MOSAIC_RET_OK || ret == Mosaic::MOSAIC_RET_FEW_INLIERS) {
	mosaic_frames.push_back(in_data);
	in_data = NULL;
      }
    } else {
      break;
    }
  }

  if (in_data) {
    delete[] in_data;
  }

  close(fd);

  std::cout << "Used " << mosaic_frames.size() << " frames" << std::endl;

  // output
  // TODO: what are those?
  float progress = 0;
  bool cancel = false;

  int64_t stitchingTime = timeNow();

  if (m.createMosaic(progress, cancel) != Mosaic::MOSAIC_RET_OK) {
    std::cerr << "Failed to stitch" << std::endl;
    return 1;
  }

  stitchingTime = timeNow() - stitchingTime;

  ImageType yuv = m.getMosaic(width, height);
  ImageType rgb = ImageUtils::allocateImage(width, height, 3);
  ImageUtils::yvu2rgb(rgb, yuv, width, height);

  for (int x = 0; x < mosaic_frames.size(); x++) {
    delete[] mosaic_frames[x];
  }

  mosaic_frames.clear();

  bool res = write_png(out, rgb, width, height);
  ImageUtils::freeImage(rgb);
  if (!res) {
    return 1;
  }

  std::cout << "Wrote mosaic image to " << out << std::endl;
  std::cout << "Width = " << width << " height = " << height << std::endl;

  if (time) {
    std::cout << "Average frame time = " << std::accumulate(times.begin(), times.end(), 0) / times.size() << "ms" << std::endl;
    std::cout << "Final stitching time = " << stitchingTime << "ms" << std::endl;
  }

  return 0;
}
std::tr1::shared_ptr<std::string> APICharacterManager::_SkillInTraining(const APICommandCall * pAPICommandCall)
{
    sLog.Error( "APICharacterManager::_SkillInTraining()", "TODO: Insert code to validate userID and apiKey" );

    sLog.Debug("APICharacterManager::_SkillInTraining()", "EVEmu API - Character Service Manager - CALL: SkillInTraining.xml.aspx");

    if( pAPICommandCall->find( "userid" ) == pAPICommandCall->end() )
    {
        sLog.Error( "APICharacterManager::_SkillInTraining()", "ERROR: No 'userID' parameter found in call argument list - exiting with error and sending back NOTHING" );
        return BuildErrorXMLResponse( "106", "Must provide userID parameter for authentication." );
    }

    if( pAPICommandCall->find( "apikey" ) == pAPICommandCall->end() )
    {
        sLog.Error( "APICharacterManager::_SkillInTraining()", "ERROR: No 'apiKey' parameter found in call argument list - exiting with error and sending back NOTHING" );
        return BuildErrorXMLResponse( "203", "Authentication failure." );
    }

    if( pAPICommandCall->find( "characterid" ) == pAPICommandCall->end() )
    {
        sLog.Error( "APICharacterManager::_SkillInTraining()", "ERROR: No 'characterID' parameter found in call argument list - exiting with error and sending back NOTHING" );
        return BuildErrorXMLResponse( "105", "Invalid characterID." );
    }

    // Make calls to the APICharacterDB class to grab all data for this call and populate the xml structure with that data
    uint32 characterID = atoi( pAPICommandCall->find( "characterid" )->second.c_str() );

    std::map<std::string, std::string> charLearningAttributesString;
    std::map<uint32, uint32> charLearningAttributes;
    m_charDB.GetCharacterAttributes( characterID, charLearningAttributesString );
    charLearningAttributes.insert( std::pair<uint32, uint32>( AttrMemory, ((uint32)(atoi(charLearningAttributesString.find(std::string(itoa(AttrMemory)))->second.c_str()))) ));
    charLearningAttributes.insert( std::pair<uint32, uint32>( AttrIntelligence, ((uint32)(atoi(charLearningAttributesString.find(std::string(itoa(AttrIntelligence)))->second.c_str()))) ));
    charLearningAttributes.insert( std::pair<uint32, uint32>( AttrCharisma, ((uint32)(atoi(charLearningAttributesString.find(std::string(itoa(AttrCharisma)))->second.c_str()))) ));
    charLearningAttributes.insert( std::pair<uint32, uint32>( AttrWillpower, ((uint32)(atoi(charLearningAttributesString.find(std::string(itoa(AttrWillpower)))->second.c_str()))) ));
    charLearningAttributes.insert( std::pair<uint32, uint32>( AttrPerception, ((uint32)(atoi(charLearningAttributesString.find(std::string(itoa(AttrPerception)))->second.c_str()))) ));

    std::vector<std::string> queueOrderList;
    std::vector<std::string> queueSkillTypeIdList;
    std::vector<std::string> queueSkillLevelList;
    std::vector<std::string> queueSkillRankList;
    std::vector<std::string> queueSkillIdList;
    std::vector<std::string> queueSkillPrimaryAttrList;
    std::vector<std::string> queueSkillSecondaryAttrList;
    std::vector<std::string> queueSkillPointsTrainedList;

    uint32 queueSkillPrimaryAttribute;
    uint32 queueSkillSecondaryAttribute;
    std::vector<uint32> queueSkillStartSP;
    std::vector<uint32> queueSkillEndSP;
    std::vector<uint64> queueSkillStartTime;
    std::vector<uint64> queueSkillEndTime;
    EvilNumber spPerMinute(0.0);
    EvilNumber skillStartSP(0.0);
    EvilNumber skillEndSP(0.0);
    EvilNumber timeNow(0.0);
    uint64 skillStartTime;
    uint64 skillEndTime;

    bool status = m_charDB.GetCharacterSkillQueue( characterID, queueOrderList, queueSkillTypeIdList, queueSkillLevelList, queueSkillRankList,
        queueSkillIdList, queueSkillPrimaryAttrList, queueSkillSecondaryAttrList, queueSkillPointsTrainedList );

    if( status )
    {
        sLog.Error( "APICharacterManager::_SkillInTraining()", "INFO: Calculation of Skill End Time based on Effective SP/min does NOT include implants/boosters at this time" );
        timeNow = EvilTimeNow();

        queueSkillPrimaryAttribute = charLearningAttributes.find( atoi(queueSkillPrimaryAttrList.at(0).c_str()) )->second;
        queueSkillSecondaryAttribute = charLearningAttributes.find( atoi(queueSkillSecondaryAttrList.at(0).c_str()) )->second;
        skillStartSP = EvilNumber(atoi( queueSkillPointsTrainedList.at(0).c_str() ));
        queueSkillStartSP.push_back( static_cast<uint32>( skillStartSP.get_int() ));
        skillEndSP = SkillPointsAtLevel( atoi(queueSkillLevelList.at(0).c_str()), atoi(queueSkillRankList.at(0).c_str()) );
        queueSkillEndSP.push_back( static_cast<uint32>( skillEndSP.get_int() ) );
        spPerMinute = SkillPointsPerMinute( queueSkillPrimaryAttribute, queueSkillSecondaryAttribute );
        skillStartTime = static_cast<uint64>(SkillStartingTime( skillStartSP, skillEndSP, spPerMinute, timeNow ).get_int());
        skillEndTime = static_cast<uint64>(SkillEndingTime( skillStartSP, skillEndSP, spPerMinute, timeNow ).get_int());
        queueSkillStartTime.push_back( skillStartTime );
        queueSkillEndTime.push_back( skillEndTime );
    }

    // EXAMPLE:
    std::vector<std::string> rowset;
    _BuildXMLHeader();
    {
        _BuildXMLTag( "result" );
        {
            if( status )
            {
                _BuildSingleXMLTag( "currentTQTime", Win32TimeToString(static_cast<uint64>(timeNow.get_int())) );
                _BuildSingleXMLTag( "trainingEndTime", Win32TimeToString(skillEndTime) );
                _BuildSingleXMLTag( "trainingStartTime", Win32TimeToString(skillStartTime) );
                _BuildSingleXMLTag( "trainingTypeID", queueSkillTypeIdList.at(0) );
                _BuildSingleXMLTag( "trainingStartSP", std::string(itoa(skillStartSP.get_int())) );
                _BuildSingleXMLTag( "trainingDestinationSP", std::string(itoa(skillEndSP.get_int())) );
                _BuildSingleXMLTag( "trainingToLevel", queueSkillLevelList.at(0) );
                _BuildSingleXMLTag( "skillInTraining", "1" );
            }
            else
            {
                _BuildSingleXMLTag( "skillInTraining", "0" );
            }
        }
        _CloseXMLTag(); // close tag "result"
    }
    _CloseXMLHeader( EVEAPI::CacheStyles::Modified );

    return _GetXMLDocumentString();
}
示例#10
0
文件: latencytask.cpp 项目: dotse/bbk
void LatencyTask::newRequest(HttpClientConnection *conn) {
    std::string lbl = std::to_string(++serial_no);
    current_request[lbl + " ok"] = timeNow();
    conn->get("/pingpong/" + lbl + "?t=" + t());
}
void VrmlNodeVisibilitySensor::render(Viewer *viewer)
{

  if (d_enabled.get())
    {
      VrmlSFTime timeNow( theSystem->time() );
      float xyz[2][3];

      // hack: enclose box in a sphere...
      xyz[0][0] = d_center.x();
      xyz[0][1] = d_center.y();
      xyz[0][2] = d_center.z();
      xyz[1][0] = d_center.x() + d_size.x();
      xyz[1][1] = d_center.y() + d_size.y();
      xyz[1][2] = d_center.z() + d_size.z();
      viewer->transformPoints( 2, &xyz[0][0] );
      float dx = xyz[1][0]-xyz[0][0];
      float dy = xyz[1][1]-xyz[0][1];
      float dz = xyz[1][2]-xyz[0][2];
      float r  = dx*dx + dy*dy + dz*dz;
      if (! FPZERO(r) ) r = sqrt( r );

      // Was the sphere visible last time through? How does this work
      // for USE'd nodes? I need a way for each USE to store whether
      // it was active.
      bool wasIn = d_isActive.get();

      // Is the sphere visible? ...
      bool inside = xyz[0][2] < 0.0; // && z > - scene->visLimit()
      if (inside)
	{
	  VrmlNodeNavigationInfo *ni = d_scene->bindableNavigationInfoTop();
	  if (ni &&
	      ! FPZERO(ni->visibilityLimit()) &&
	      xyz[0][2] < - ni->visibilityLimit())
	    inside = false;
	}

      // This bit assumes 90degree fieldOfView to get rid of trig calls...
      if (inside)
	inside = ( fabs(double(xyz[0][0])) < -0.5 * xyz[0][2] + r &&
		   fabs(double(xyz[0][1])) < -0.5 * xyz[0][2] + r );

      // Just became visible
      if (inside && ! wasIn)
	{
	  theSystem->debug("VS enter %g, %g, %g\n",
			xyz[0][0], xyz[0][1], xyz[0][2]);

	  d_isActive.set(true);
	  eventOut(timeNow.get(), "isActive", d_isActive);

	  d_enterTime = timeNow;
	  eventOut(timeNow.get(), "enterTime", d_enterTime);
	}

      // Check if viewer has left the box
      else if (wasIn && ! inside)
	{
	  theSystem->debug("VS exit %g, %g, %g\n",
			xyz[0][0], xyz[0][1], xyz[0][2]);

	  d_isActive.set(false);
	  eventOut(timeNow.get(), "isActive", d_isActive );

	  d_exitTime = timeNow;
	  eventOut(timeNow.get(), "exitTime", d_exitTime);
	}
    }

  else
    clearModified();
}
示例#12
0
void Timer::stop (){ mStop  = timeNow(); }
示例#13
0
void Timer::start(){ mStart = timeNow(); }
示例#14
0
nsec_t sleepUntil(nsec_t t){
	nsec_t now = timeNow();
	if(t > now) sleep(t - now);
	return t - now;
}
int main (int argc, char* argv[]) {
  if (argc < 3) {
    std::cout << "Need HOST and PORT as command line arguments." << std::endl;
    return 1;
  }
  if (argc >= 4) {
    N = atoi(argv[3]);
  }
  std::string resulturl;
  if (argc >= 5) {
    resulturl = argv[4];
  }

  std::cout << "ArangoDB latency test, calling " << N 
            << " times GET /_api/document/c/mykey" << std::endl;

  std::vector<uint64_t> timings;
  timings.reserve(N);

  std::string url = std::string("http://") + argv[1] + ":" + argv[2];
  std::string urlcomplete;

  curl_global_init(CURL_GLOBAL_DEFAULT);
  CURL* h = curl_easy_init();

  // Delete the collection c:
  std::cout << "Dropping collection c..." << std::endl;
  curl_easy_setopt(h, CURLOPT_CUSTOMREQUEST, "DELETE");
  urlcomplete = url + "/_api/collection/c";
  curl_easy_setopt(h, CURLOPT_URL, urlcomplete.c_str());
  curl_easy_perform(h);
  curl_easy_setopt(h, CURLOPT_CUSTOMREQUEST, NULL);
  std::cout << "\ndone." << std::endl;

  std::cout << "Creating collection c..." << std::endl;
  strcpy(buffer, "{\"name\": \"c\", \"numberOfShards\":13}");
  urlcomplete = url + "/_api/collection";
  curl_easy_setopt(h, CURLOPT_URL, urlcomplete.c_str());
  struct curl_slist *headers=NULL;
  headers = curl_slist_append(headers, "Content-Type: application/json");
  curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
  curl_easy_setopt(h, CURLOPT_POSTFIELDS, buffer);
  curl_easy_setopt(h, CURLOPT_POSTFIELDSIZE, strlen(buffer));
  curl_easy_perform(h);
  curl_slist_free_all(headers);
  headers = NULL;
  std::cout << "\ndone." << std::endl;

  std::cout << "Creating one document..." << std::endl;
  strcpy(buffer, "{\"_key\":\"mykey\", \"name\":\"Neunhöffer\", \"firstName\":\"Max\"}");
  urlcomplete = url + "/_api/document?collection=c";
  curl_easy_setopt(h, CURLOPT_URL, urlcomplete.c_str());
  headers = curl_slist_append(headers, "Content-Type: application/json");
  curl_easy_setopt(h, CURLOPT_HTTPHEADER, headers);
  curl_easy_setopt(h, CURLOPT_POSTFIELDS, buffer);
  curl_easy_setopt(h, CURLOPT_POSTFIELDSIZE, strlen(buffer));
  curl_easy_perform(h);
  curl_slist_free_all(headers);
  std::cout << "\ndone." << std::endl;

  curl_easy_setopt(h, CURLOPT_HTTPGET, 1);
  curl_easy_setopt(h, CURLOPT_HTTPHEADER, NULL);
  curl_easy_setopt(h, CURLOPT_TCP_NODELAY, 1);

  std::cout << "Now racing..." << std::endl;
  timePointType t = timeNow();
  urlcomplete = url + "/_api/document/c/mykey";
  curl_easy_setopt(h, CURLOPT_URL, urlcomplete.c_str());
  curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, write_data);
  timePointType t3, t4;
  for (int i = 0; i < N; i++) {
    pos = 0;
    t3 = timeNow();
    int success = curl_easy_perform(h);
    t4 = timeNow();
    timings.push_back(timeDiff(t3,t4));
    buffer[pos] = 0;
  }
  curl_easy_cleanup(h);
  timePointType t2 = timeNow();
  uint64_t d = timeDiff(t,t2);
  std::cout << "Total time: " << d << " ns" << std::endl;
  analyzeTimings("arangoTestDocument" + std::to_string(getpid()) 
                 + ".times", timings, N);
  dumpTimings("arangoTestDocument" + std::to_string(getpid()) 
              + ".times", timings);
  if (! resulturl.empty()) {
    submitTimings(resulturl, "readDocument", timings, N-1);
  }
  return 0;
}
示例#16
0
文件: bot.cpp 项目: heihachi/IRC-Bot
bool IrcBot::bot()
{
    char *text;
    char buf[1024];
    int bytes_read;
    int bytes_send;

    string sendCommands[5] = { "PONG", "USER "+userName+" 8 * :"+userName, "NICK "+nickName, "PRIVMSG nickserv identify "+userPass, "JOIN "+channelName };

    printf("Connecting to %s:%s\nNick: %s | Channel: %s\n", hostName.c_str(), portString.c_str(), nickName.c_str(), channelName.c_str());

    ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
                    *ptr = NULL,
                    hints;
    const char *sendbuf = "\nPONG :Bot\n";
    char recvbuf[DEFAULT_BUFLEN] = { };
    int recvbuflen = DEFAULT_BUFLEN;

    #ifdef WIN32
    // start WinSock Initialization
    WSADATA wsaData;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }
    #endif // WIN32

    ZeroMemory( &hints, sizeof(hints) );
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    // Resolve the server address and port
    iResult = getaddrinfo(hostName.c_str(), portString.c_str(), &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        #ifdef WIN32
        WSACleanup();
        #endif // WIN32
        return 1;
    }

    // Attempt to connect to an address until one succeeds
    for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {

        // Create a SOCKET for connecting to server
        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("socket failed with error: %ld\n", WSAGetLastError());
            WSACleanup();
            return 1;
        }

        // Connect to server.
        iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR)
        {
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);

    if (ConnectSocket == INVALID_SOCKET) {
        printf("Unable to connect to server!\n");
        #ifdef WIN32
        WSACleanup();
        #endif // WIN32
        return 1;
    }

    // Send an initial buffer
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if(DEBUG == true)
        printf("Sendbuf: %s\n", sendbuf);
    if (iResult == SOCKET_ERROR)
    {
        #ifdef WIN32
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        #endif // WIN32
        return 1;
    }

    printf("Bytes Sent: %ld\n", iResult);

    // Receive until the peer closes the connection
    int count = 0;
    while(1)
    {
        count++;

        switch(count)
        {
            case 2:
                // we send data to server after 3 counts
                // nick
                sendCommand(ConnectSocket, "\nUSER %s Bot Bot : %s\n", userName.c_str(), userName.c_str());
                // user
                sendCommand(ConnectSocket, "\nNICK %s\r\n", nickName.c_str());
                break;
            case 11:
                // register
                sendCommand(ConnectSocket, "\nPRIVMSG nickserv identify %s\r\n", userPass.c_str());
                break;
            case 12:
                // we join channel
                sendCommand(ConnectSocket, "\nJOIN %s\r\n", channelName.c_str());
            default:
                break;
        }

        // Recv and print data
        bytes_read = recv(ConnectSocket, buf, MAXDATASIZE-1, 0);
        buf[bytes_read]='\0';
        cout << buf << endl;
        // buf is the data that is recieved

        // pass buffer to message handler
        msgHandler(buf);

        // if we get ping
        if(charSearch(buf,"PING"))
        {
            sendPong(buf);
        }

        //break if connection closed
        if(bytes_read == 0)
        {
            cout << "Connection closed!" << endl;
            cout << timeNow() << endl;

            break;
        }
    }
#ifdef WIN32
    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();
#elif LINUX
    close(ConnectSocket);
#endif
    return true;
}