// This is the main driver program for the time and date server. int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { Server<AccountManager_i> server; ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n\tBank server\n\n"))); try { if (server.init ("Bank", argc, argv) == -1) return 1; else { server.run (); } } catch (const CORBA::UserException& userex) { userex._tao_print_exception ("User Exception"); return -1; } catch (const CORBA::SystemException& sysex) { sysex._tao_print_exception ("System Exception"); return -1; } catch (const ::CORBA::Exception &e) { e._tao_print_exception ("CORBA exception"); return 1; } return 0; }
bool LoginLayerUC::checkServerStatus(const Server &server) { switch (server.server_status()) { //未开启状态 case 0: { tm tm ; time_t timep = server.open_time()/1000; tm = *localtime(&timep); int year = tm.tm_year + 1900; int month = tm.tm_mon + 1; int day = tm.tm_mday; int hour= tm.tm_hour; int minute = tm.tm_min; int second = tm.tm_sec; CCString* sDay = CCString::createWithFormat("%d/%s%d/%s%d-%s%d:%s%d:%s%d", year, month>9?"":"0", month, day>9?"":"0", day, hour>9?"":"0", hour, minute>9?"":"0", minute, second>9?"":"0", minute); CCString* pStr = CCString::createWithFormat(GETLANGSTR(2001), sDay->getCString()); ShowPopTextTip(pStr->getCString()); return false; }break; case 4: { //服务器是维护状态,不连接,给提示 ShowPopTextTip(GETLANGSTR(1243)); return false; }break; default: break; } return true; }
/* * Attempts to send the requested page for the current connection */ void sendPage() { // Reset the virtual buffer cursor uip_conn->appstate.cursor = 0; // Start off with an HTTP OK response header and a blank line WiServer.println_P(httpOK); WiServer.println(); // Call the application's 'sendPage' function and ask it to // generate the requested page content. if (!callbackFunc((char*)uip_conn->appstate.request)) { // The URL is not recognized by the sketch // Reset the cursor and overwrite the HTTP OK header with a 404 message uip_conn->appstate.cursor = 0; WiServer.println_P(httpNotFound); WiServer.println(); #ifdef DEBUG Serial.println("URL Not Found"); #endif // DEBUG } // Send the 'real' bytes in the buffer send(); }
void AddMetaNodeExecutor::execute_server() { int count, id; QString name, edgeName; float x, y, z; *stream >> name; Data::Graph * currentGraph = Manager::GraphManager::getInstance()->getActiveGraph(); QMap<qlonglong, osg::ref_ptr<Data::Node> >* nodes = currentGraph -> getNodes(); *stream >> x >> y >> z; osg::ref_ptr<Data::Node> metaNode = currentGraph->addNode(name, currentGraph->getNodeMetaType(), osg::Vec3(x,y,z)); *stream >> edgeName; *stream >> count; QLinkedList<osg::ref_ptr<Data::Node> > * selectedNodes = new QLinkedList<osg::ref_ptr<Data::Node> >(); for (int i = 0; i < count; i++) { *stream >> id; if (nodes->contains(id)) { currentGraph->addEdge(edgeName, *nodes->find(id), metaNode, currentGraph->getEdgeMetaType(), true); selectedNodes->append(*nodes->find(id)); } } Server * server = Server::getInstance(); server->sendAddMetaNode(metaNode,selectedNodes,edgeName,osg::Vec3(x,y,z)); if (((QOSG::CoreWindow *)server->getCoreWindowReference())->playing()) { server->getLayoutThread()->play(); } }
void RemoveEdgeExecutor::execute_server() { int id; *stream >> id; Data::Graph* currentGraph = Manager::GraphManager::getInstance()->getActiveGraph(); QMap<qlonglong, osg::ref_ptr<Data::Edge> >* edges = currentGraph -> getEdges(); if ( edges->contains( id ) ) { Data::Edge* edge = *edges->find( id ); if ( edge != NULL ) { currentGraph->removeEdge( edge ); } } Server* server = Server::getInstance(); server->sendRemoveEdge( id ); if ( ( ( QOSG::CoreWindow* )server->getCoreWindowReference() )->playing() ) { server->getLayoutThread()->play(); } }
TaskBuoyInnerClass(std::string name, std::string node, std::string node1, std::string node2, std::string node3) : buoy_server_(nh_, name, boost::bind(&TaskBuoyInnerClass::analysisCB, this, _1), false) , action_name_(name) , ForwardClient_(node) , SidewardClient_(node1) , UpwardClient_(node2) , TurnClient_(node3) { ROS_INFO("inside constructor"); buoy_server_.registerPreemptCallback(boost::bind(&TaskBuoyInnerClass::preemptCB, this)); switch_buoy_detection = nh_.advertise<std_msgs::Bool>("buoy_detection_switch", 1000); present_X_ = nh_.advertise<std_msgs::Float64>("/varun/motion/y_distance", 1000); present_Y_ = nh_.advertise<std_msgs::Float64>("/varun/motion/z_distance", 1000); present_distance_ = nh_.advertise<std_msgs::Float64>("/varun/motion/x_distance", 1000); yaw_pub_ = nh_.advertise<std_msgs::Float64>("/varun/motion/yaw", 1000); sub_ip_ = nh_.subscribe<std_msgs::Float64MultiArray>("/varun/ip/buoy", 1000, &TaskBuoyInnerClass::buoyNavigation, this); yaw_sub_ = nh_.subscribe<std_msgs::Float64>("/varun/sensors/imu/yaw", 1000, &TaskBuoyInnerClass::yawCB, this); pressure_sensor_sub = nh_.subscribe<std_msgs::Float64>("/varun/sensors/pressure_sensor/depth", 1000, &TaskBuoyInnerClass::pressureCB, this); buoy_server_.start(); }
bool test_enums() { printf("\n*** test_enums()\n"); Network yarp; yarp.setLocalMode(true); Demo client; Server server; Port client_port,server_port; client_port.open("/client"); server_port.open("/server"); yarp.connect(client_port.getName(),server_port.getName()); client.yarp().attachAsClient(client_port); server.yarp().attachAsServer(server_port); std::vector<DemoEnum> lst1; lst1.push_back(ENUM1); lst1.push_back(ENUM2); std::vector<DemoEnum> lst2 = client.test_enum_vector(lst1); printf("lst1 %d lst2 %d\n", lst1.size(), lst2.size()); return (lst2.size()==3 && lst1[0]==lst2[0] && lst1[1]==lst2[1]); }
int main(int argc, char ** argv) { if(argc != 2) { printf("Usage: %s number-of-clients\n", argv[0]); exit(1); } int clientsNumber = atoi(argv[1]); require(clientsNumber >= 3 && clientsNumber <= 6, "The numbers of clients in a game should be between 3 and 6.\n"); Table::TABLE_SIZE = clientsNumber; Table table; Server server; while(true) { const int n = server.poll(); //there are n new incoming connections for(int i = 0; i < n; ++i) { const int client = server.acceptConnection(); if(table.GAME_END) { Table newTable; table = newTable; } table.addPlayer(client); } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } return 0; }
UDPAllocation::UDPAllocation(Server& server, const FiveTuple& tuple, const std::string& username, const UInt32& lifetime) : ServerAllocation(server, tuple, username, lifetime)//, //_relaySocket(new net::UDPSocket) //server.reactor(), server.runner() { // Handle data from the relay socket directly from the allocation. // This will remove the need for allocation lookups when receiving // data from peers. _relaySocket.bind(net::Address(server.options().listenAddr.host(), 0)); _relaySocket.Recv += sdelegate(this, &UDPAllocation::onPeerDataReceived); TraceL << " Initializing on address: " << _relaySocket.address() << endl; }
int main(int argc, char** argv) { uid_t uID = getuid(); if(uID != 0) { std::cout << "You are not running as root, this will cause problems.\n"; } server.startX(); while(!server.pollServer()) { usleep(5*1000); } QApplication app(argc, argv); double ppi = app.primaryScreen()->physicalDotsPerInch(); //std::cout << "Your ppi is " << ppi << "\n"; Window window; if(ppi >= 200.00) { /* HiDPI ** some hidpi font setting hack ** Qt5 should be getting proper hidpi support on linux soon? */ window.isHiDPI(true); QFont font = app.font(); font.setPointSize(font.pointSize()*2); app.setFont(font); } window.resize(app.primaryScreen()->size()); window.setWindowFlags(Qt::FramelessWindowHint); window.update(); window.show(); return app.exec(); }
/* * NICK - NEW * Received: :dev.anope.de NICK DukeP_ 1 ~DukePyro ip-2-201-236-154.web.vodafone.de 1 + :DukePyrolator * Parameters: <nickname> <hopcount> <username> <host> <servertoken> <umode> :<realname> * source = server * params[0] = nick * params[1] = hopcount * params[2] = username/ident * params[3] = host * params[4] = servertoken * params[5] = modes * params[6] = info * * NICK - change * Received: :DukeP_ NICK :test2 * source = oldnick * params[0] = newnick * */ void Run(MessageSource &source, const std::vector<Anope::string> ¶ms) override { if (params.size() == 1) { // we have a nickchange source.GetUser()->ChangeNick(params[0]); } else if (params.size() == 7) { // a new user is connecting to the network Server *s = Server::Find(params[4]); if (s == NULL) { Log(LOG_DEBUG) << "User " << params[0] << " introduced from non-existent server " << params[4] << "?"; return; } User::OnIntroduce(params[0], params[2], params[3], "", "", s, params[6], Anope::CurTime, params[5], "", NULL); Log(LOG_DEBUG) << "Registered nick \"" << params[0] << "\" on server " << s->GetName() << "."; } else { Log(LOG_DEBUG) << "Received NICK with invalid number of parameters. source = " << source.GetName() << "params[0] = " << params[0] << "params.size() = " << params.size(); } }
// rollback_get_node_actions(pos, range, seconds, limit) -> {{actor, pos, time, oldnode, newnode}, ...} int ModApiRollback::l_rollback_get_node_actions(lua_State *L) { v3s16 pos = read_v3s16(L, 1); int range = luaL_checknumber(L, 2); time_t seconds = (time_t) luaL_checknumber(L, 3); int limit = luaL_checknumber(L, 4); Server *server = getServer(L); IRollbackManager *rollback = server->getRollbackManager(); std::list<RollbackAction> actions = rollback->getNodeActors(pos, range, seconds, limit); std::list<RollbackAction>::iterator iter = actions.begin(); lua_createtable(L, actions.size(), 0); for (unsigned int i = 1; iter != actions.end(); ++iter, ++i) { lua_createtable(L, 0, 5); // Make a table with enough space pre-allocated lua_pushstring(L, iter->actor.c_str()); lua_setfield(L, -2, "actor"); push_v3s16(L, iter->p); lua_setfield(L, -2, "pos"); lua_pushnumber(L, iter->unix_time); lua_setfield(L, -2, "time"); push_RollbackNode(L, iter->n_old); lua_setfield(L, -2, "oldnode"); push_RollbackNode(L, iter->n_new); lua_setfield(L, -2, "newnode"); lua_rawseti(L, -2, i); // Add action table to main table } return 1; }
static QString serverHtmlLabel(const Server &s) { // No server info available QString label = s.label(); if (s.uuid().isEmpty() && s.version().isEmpty()) label = s.nativeUrl(); if (s.label().isEmpty()) label = tkTr(Trans::Constants::_1_COLON_2).arg(tkTr(Trans::Constants::UNKNOWN_SERVER)).arg(s.nativeUrl()); label = QString("<span style=\"color:black;font-weight:bold;\">%1</span>") .arg(label); if (s.isConnected()) { if (s.lastChecked().isValid()) label += QString("<br /><span style=\"color:gray; font-size:small;\">%2 (%3: %4)</span>") .arg(tkTr(Trans::Constants::CONNECTED)) .arg(tkTr(Trans::Constants::LAST_CHECK)) .arg(s.lastChecked().toString(QLocale().dateFormat(QLocale::LongFormat))); else label += QString("<br /><span style=\"color:gray; font-size:small;\">%2</span>") .arg(tkTr(Trans::Constants::CONNECTED)); } else { label += QString("<br /><span style=\"color:gray; font-size:small;\">%2</span>") .arg(tkTr(Trans::Constants::NOT_CONNECTED)); } label += QString("<br /><span style=\"color:gray; font-size:small;\">%1 %2</span>") .arg(serverManager()->getPackForServer(s).count()) .arg(tkTr(Trans::Constants::PACKAGES)); if (!s.errors().isEmpty()) { label += QString("<br /><span style=\"color:marron; font-size:small;\">%1: %2</span>") .arg(tkTr(Trans::Constants::ERRORS)) .arg(s.errors().count()); } return label; }
TEST (TestServer, DefineStream) { Server server; try { std::stringstream is1("CREATE STREAM TESTSTREAM1(ID INT, NAME STRING)"); InputStreamHandler::ptr_t test_stream1 = define_stream_from_ddl(server, is1); EXPECT_TRUE(server.has_stream_with_name("TESTSTREAM1")); std::stringstream is2("CREATE STREAM TESTSTREAM2(ID INT, NAME STRING, AGE INT)"); InputStreamHandler::ptr_t test_stream2 = define_stream_from_ddl(server, is2); EXPECT_TRUE(server.has_stream_with_name("TESTSTREAM2")); server.get_stream_adapter_by_name("TESTSTREAM1"); server.get_stream_adapter_by_name("TESTSTREAM2"); // server.register_query( // "QUERY1", // "TESTSTREAM1", // Operator::ptr_t( // new OperatorStreamAdapter(server.get_stream("TESTSTREAM1")) // ) // ); // server.register_query_legacy( // "QUERY1", // Operator::ptr_t( // server.get_stream_adapter_by_name("TESTSTREAM1") // ) // ); } catch (std::string error) { std::cout << error << std::endl; EXPECT_TRUE(false); } // EXPECT_EQ(); }
// From ServerApplication void run() { // Require a valid certificate from client sslCtx.setVerifyPeer(true, true); // Load certificates and keys sslCtx.useCertificateChainFile("server.pem"); sslCtx.usePrivateKey(InputSource("server.pem")); //sslCtx.addTrustedCA("root.pem"); //sslCtx.addCRL("crl.pem"); // Test BIMemory uint64_t length = SystemUtilities::getFileSize("root.pem"); SmartPointer<iostream> f = SystemUtilities::open("root.pem", ios::in); SmartPointer<char> buf = new char[length]; f->read(buf.get(), length); if (f->fail()) THROWS("Failed reading root.pem"); BIMemory bio(buf.get(), length); sslCtx.addTrustedCA(bio.getBIO()); server.start(); while (!quit) Timer::sleep(0.1); server.join(); }
Player::Player(const std::string& name, boost::uuids::uuid uuid, std::shared_ptr<Session> session, std::int32_t id, Server& server, World* world, Gamemode gamemode) : HasServer(server), CommandSender(commands::CommandSenderType::Player), mUUID(uuid), mNickname(name), mWorld(world), session(session), gamemode(gamemode), mSendKeepAliveTimer(server.getWorkIO()), mTeleportID(0), mEntityID(id), hasSavedToDisk(false) { Logger::debug((boost::format("Player %1% created") % this).str()); loadFromFile(); mLastPositionWhenChunksWasSent.x = 0; mLastPositionWhenChunksWasSent.z = 0; }
IndexerJob::IndexerJob(const Source &s, Flags<Flag> f, const std::shared_ptr<Project> &p, const UnsavedFiles &u) : id(0), source(s), sourceFile(s.sourceFile()), flags(f), project(p->path()), priority(0), unsavedFiles(u), crashCount(0) { acquireId(); if (flags & Dirty) ++priority; Server *server = Server::instance(); assert(server); if (server->isActiveBuffer(source.fileId)) { priority += 4; } else { for (uint32_t dep : p->dependencies(source.fileId, Project::ArgDependsOn)) { if (server->isActiveBuffer(dep)) { priority += 2; break; } } } visited.insert(s.fileId); }
static bool is_blocked(Server &server, const epee::net_utils::network_address &address, time_t *t = NULL) { const std::string host = address.host_str(); std::map<std::string, time_t> hosts = server.get_blocked_hosts(); for (auto rec: hosts) { if (rec.first == host) { if (t) *t = rec.second; return true; } } return false; }
int main() { // Step1: 创建一个Server对象 Server server; // Step2: 设置ssl参数, 使用ssl之前, 需要先安装openssl, 并在编译libgonet时使用如下CMake参数: // $ cmake .. -DENABLE_SSL=ON // // 编译程序时, 请链接openssl: -lssl -lcrypto #if ENABLE_SSL OptionSSL ssl_opt; ssl_opt.certificate_chain_file = "../sslopt/server.crt"; ssl_opt.private_key_file = "../sslopt/server.key"; ssl_opt.tmp_dh_file = "../sslopt/dh2048.pem"; server.SetSSLOption(ssl_opt); #endif // Step3: 设置收到数据的处理函数 server.SetReceiveCb(&OnMessage); // Step3: 启动server boost_ec ec = server.goStart("ssl://127.0.0.1:3030"); // Step4: 处理goStart返回值, 检测是否启动成功 if (ec) { printf("server start error %d:%s\n", ec.value(), ec.message().c_str()); return 1; } else { boost_ec ignore_ec; printf("server start at %s\n", server.LocalAddr().to_string(ignore_ec).c_str()); } // Step5: 启动协程调度器 co_sched.RunUntilNoTask(); return 0; }
void setup() { //Serial.begin(9600); PgmPrint("Free RAM: "); //Serial.println(FreeRam()); // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with // breadboards. use SPI_FULL_SPEED for better performance. pinMode(10, OUTPUT); // set the SS pin as an output (necessary!) digitalWrite(10, HIGH); // but turn off the W5100 chip! if (!card.init(SPI_HALF_SPEED, 4)) error("card.init failed!"); // initialize a FAT volume if (!volume.init(&card)) error("vol.init failed!"); PgmPrint("Volume is FAT"); //Serial.println(volume.fatType(),DEC); //Serial.println(); if (!root.openRoot(&volume)) error("openRoot failed"); // list file in root with date and size PgmPrintln("Files found in root:"); root.ls(LS_DATE | LS_SIZE); //Serial.println(); // Recursive list of all directories PgmPrintln("Files found in all dirs:"); root.ls(LS_R); //Serial.println(); PgmPrintln("Done"); // Debugging complete, we start the server! Ethernet.begin(mac, ip); server.begin(); // Start up the temperature library sensorsa.begin(); sensorsb.begin(); sensorsc.begin(); sensorsd.begin(); setTime(0); // start the clock time33mins = time60mins = now(); }
virtual ::grpc::Status insert(::grpc::ServerContext* context, const api::InsertRequest* request, api::InsertResponse* response) { InsertRequest req; req.db = request->db(); req.key = request->key(); req.raw = request->raw(); req.url = request->url(); req.content = request->content(); InsertResponse resp; server->insert(req, &resp); response->set_time(resp.time); response->set_load_time(resp.load_time); response->set_journal_time(resp.journal_time); response->set_index_time(resp.index_time); return grpc::Status::OK; }
MCResult MemCacheClient::IncDec( const char * aType, unsigned aService, const char * aKey, uint64_t * aNewValue, uint64_t aDiff, bool aWantReply ) { string_t key(aKey); Server * pServer = FindServer(key, aService); if (!pServer) return MCERR_NOSERVER; char szBuf[50]; string_t sRequest(aType); sRequest += ' '; sRequest += aKey; snprintf(szBuf, sizeof(szBuf), " %" PRIu64, aDiff); sRequest += szBuf; if (!aWantReply) { sRequest += " noreply"; } sRequest += "\r\n"; try { pServer->SendBytes(sRequest.data(), sRequest.length()); if (!aWantReply) { return MCERR_NOREPLY; } string_t sValue; sValue = pServer->GetByte(); while (sValue[sValue.length()-1] != '\n') { sValue += pServer->GetByte(); } if (sValue == "NOT_FOUND\r\n") { return MCERR_NOTFOUND; } if (aNewValue) { *aNewValue = strtoull(sValue.data(), NULL, 10); } return MCERR_OK; } catch (const Socket::Exception & e) { mTrace.Trace(CLINFO, "IncDec: error '%s' at %s, marking request as NOSERVER", e.mDetail, pServer->GetAddress()); pServer->Disconnect(); return MCERR_NOSERVER; } }
/* ================================================================== * * Function: web_input * Description: Static callback function to handle input to the server * Parameters: See Webduino documentation * obj is a pointer to the instance of Server that added the callback * ================================================================== */ void web_input(WebServer &server, WebServer::ConnectionType type, char * c, bool b, void * obj) { if (type == WebServer::POST) { Server * s = (Server *) obj; bool repeat; char name[16], value[16]; do { // Read all POST params, returns false when no more params repeat = server.readPOSTparam(name, 16, value, 16); if (strcmp(name, "visualizer") == 0) { int type = strtol(value, NULL, 10); // Ensure type is valid, default to VISUALIZER_BARS switch (type) { case VISUALIZER_BARS: case VISUALIZER_BARS_MIDDLE: case VISUALIZER_PULSE: case VISUALIZER_PLASMA: case VISUALIZER_RAINBOW: case VISUALIZER_WHEEL: s->set_visualizer(type); break; default: s->set_visualizer(VISUALIZER_BARS); break; } } else if (strcmp(name, "other") == 0) { int type = strtol(value, NULL, 10); // Ensure type is valid, default to BOUNCING_LINES switch (type) { case BOUNCING_LINES: case BAR_TEST: case PIXEL_TEST: case AMBIENT_LIGHTING: s->set_visualizer(type); break; default: s->set_visualizer(BOUNCING_LINES); break; } } else if (strcmp(name, "power") == 0) { s->set_power(strtol(value, NULL, 10)); } } while (repeat); // after procesing the POST data, tell the web browser to reload // the page using a GET method. server.httpSeeOther("/web_input"); return; } /* for a GET or HEAD, send the standard "it's all OK headers" */ server.httpSuccess(); /* we don't output the body for a HEAD request */ if (type == WebServer::GET) { server.printP(control_panel); } }
void handleReqAbort(struct CommitIdPacket *req) { int reqAbortId = ntohl(req->commitId); int currentCommitId = M.lastCommitId_ + 1; if(currentCommitId < 0) currentCommitId = 0; if(currentCommitId <= reqAbortId) { for(size_t i=0; i < MAX_WRITE_STAGE; ++i) { M.stagedWrites[i].writeSeq = -1; } M.lastCommitId_ = reqAbortId; M.readyToCommit_ = false; M.totalWriteCount_ = 0; } if(M.lastCommitId_ == reqAbortId) { M.sendServerIdPacket(ACK_ABORT); } }
int MemCacheClient::FlushAll( const char * aServer, int aExpiry ) { char szRequest[50]; snprintf(szRequest, sizeof(szRequest), "flush_all %u\r\n", aExpiry); Server test(mTrace); if (aServer && !test.Set(aServer)) { return false; } int nSuccess = 0; for (size_t n = 0; n < mServer.size(); ++n) { Server * pServer = mServer[n]; if (aServer && *pServer != test) continue; // ensure that we are connected if (pServer->Connect(mTimeoutMs, mRetryMs) != Server::CONNECT_SUCCESS) { continue; } try { // request pServer->SendBytes(szRequest, strlen(szRequest)); // response string_t sValue; sValue = pServer->GetByte(); while (sValue[sValue.length()-1] != '\n') { sValue += pServer->GetByte(); } if (sValue == "OK\r\n") { // done ++nSuccess; } else { // unknown response, connection may be bad pServer->Disconnect(); } } catch (const Socket::Exception &) { mTrace.Trace(CLINFO, "socket error, ignoring flush request"); // data error } } return nSuccess; }
void insert(api::InsertResponse& response, const api::InsertRequest& request) { protect([this, &response, request](){ InsertRequest req; req.db = request.db; req.key = request.key; req.meta = request.meta; req.raw = request.raw; req.url = request.url; req.content = request.content; InsertResponse resp; server->insert(req, &resp); response.time=resp.time; response.load_time=resp.load_time; response.journal_time=resp.journal_time; response.index_time=resp.index_time; }); }
void Mensa::OnEvent(Server& srv, const std::string& event, const std::string& origin, const std::vector<std::string>& params) { if(params.size() == 0) throw std::logic_error("OnEvent should only be called for SENDMSG"); int offset = 0; if(params.size() > 1 && !params[1].empty()) { std::stringstream sstr(params[1]); sstr >> offset; if(sstr.fail()) { srv.SendMsg(params[0], "Error: " + params[1] + " is not a number"); return; } }
void listenForClients() { // listen for incoming clients Client client = server.available(); if (client) { Serial.println("Got a client"); // an http request ends with a blank line boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { char c = client.read(); // if you've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so you can send a reply if (c == '\n' && currentLineIsBlank) { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(); // print the current readings, in HTML format: client.print("Temperature: "); client.print(temperature); client.print(" degrees C"); client.println("<br />"); client.print("Pressure: " + String(pressure)); client.print(" Pa"); client.println("<br />"); break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); } }
void loop() { // Turn the LED on ... nice to see something is working. digitalWrite(ledPin, HIGH); // set the LED on Client client = server.available(); if (client) { // an http request ends with a blank line boolean current_line_is_blank = true; while (client.connected()) { if (client.available()) { char c = client.read(); // if we've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so we can send a reply if (c == '\n' && current_line_is_blank) { // send a standard http response header // HTTP header client.println("HTTP/1.1 200 OK"); //TODO client.println("Content-Type: text/html"); client.println("Content-Type: text/plain"); client.println(); // output the value of each analog input pin client.println("off"); } break; } if (c == '\n') { // we're starting a new line current_line_is_blank = true; } else if (c != '\r') { // we've gotten a character on the current line current_line_is_blank = false; } } } // give the web browser time to receive the data delay(1000); client.stop(); }
TCPServer::TCPServer( boost::asio::io_service & io ) :m_acceptor(io,tcp::endpoint(tcp::v4(),SRV_PORT_DEFAULT)) { Server *srv = Server::GetInstance(); GameAttack* t_attack = srv->GetGameAttack(); Monster* t_monster = srv->GetMonster(); OperationPostgres* t_opePost = srv->GetOperationPostgres(); //技能伤害线程 srv->RunTask(boost::bind(&GameAttack::RoleSkillAttack, t_attack)); //怪物复活线程 srv->RunTask(boost::bind(&Monster::MonsterSpawns, t_monster)); //删除过了时间的掉落物品 srv->RunTask(boost::bind(&GameAttack::DeleteOverTimeGoods, t_attack)); //操作数据库更新用户数据 srv->RunTask(boost::bind(&OperationPostgres::UpdatePlayerData, t_opePost)); }