void OnMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time_) { LOG_DEBUG << conn->name(); size_t len = buf->readableBytes(); while (len >= kCells + 2) { const char* crlf = buf->findCRLF(); if (crlf) { kimgbo::string request(buf->peek(), crlf); buf->retrieveUntil(crlf + 2); len = buf->readableBytes(); if (!processRequest(conn, request)) { conn->send("Bad Request!\r\n"); conn->shutdown(); break; } } else if (len > 100) // id + ":" + kCells + "\r\n" { conn->send("Id too long!\r\n"); conn->shutdown(); break; } else { break; } } }
bool processRequest(const TcpConnectionPtr& conn, const string& request){ string id; string puzzle; bool goodRequest = true; string::const_iterator colon = find(request.begin(), request.end(), ':'); if(colon != request.end()){ id.assign(request.begin(), colon); puzzle.assign(colon+1, request.end()); }else{ puzzle = request; } if(puzzle.size() == implicit_cast<size_t>(kCells)){ LOG_DEBUG << conn->name(); string result = solveSudoku(puzzle); if(id.empty()){ conn->send(result+"\r\n"); }else{ conn->send(id +":"+ result+"\r\n" ); } }else goodRequest = false; return goodRequest; }
void EchoServer::onConnect(const TcpConnectionPtr &conn) { cout << "client : " << conn->getPeerAddr().toIp() << " : " << conn->getPeerAddr().toPort() << " on" << endl; conn->send("hello, welcome to Echo Server!\r\nenter word to look for, or q to quit: "); }
void ZGWServer::responseMsg(zmq_msg_t& msg_t) { size_t msg_size = zmq_msg_size(&msg_t); assert( msg_size > 0 ); std::string str_msg(static_cast<char*>(zmq_msg_data(&msg_t)), msg_size); ZMSG msg; int rc = msg.deserialize(str_msg); if( rc != 0 ) { LOG_ERROR << "PULL线程反序列化消息失败, ret: " << rc; return; } //LOG_INFO << "PULL线程反序列化消息成功, msg[id]: " << msg.flow_id << ", msg[type]: " // << msg.msg_type << ", msg[body size]:" << msg.msg_body.size(); std::map<uint32_t, TcpConnectionPtr>::iterator iter = id2conn_.find(msg.flow_id); if( iter == id2conn_.end() ) { LOG_ERROR << "PULL线程查找flow_id: " << msg.flow_id << "对应的连接失败"; return; } TcpConnectionPtr conn = iter->second; muduo::net::Buffer buf; buf.prependInt8(msg.msg_type); buf.prependInt32(static_cast<int32_t>(msg.msg_body.size())); buf.append(msg.msg_body.c_str(), msg.msg_body.size()); conn->send(&buf); stat_.msg_recv_cnt.increment(); stat_.msg_recv_bytes.addAndGet(msg_size); }
void EchoServer::compute(const std::string &word, const TcpConnectionPtr &conn, const TextQuery &tq) { if(word == "q") exit(0); typedef set<TextQuery::line_no> line_nums; line_nums locs = tq.run_query(word); line_nums::size_type size = locs.size(); char ssize[128] = ""; sprintf(ssize, "%d", size); string s; s = s + "\n" + word + " occurs " + ssize + " " + make_plural(size, "time", "s") + "\n"; line_nums::const_iterator it = locs.begin(); for ( ; it != locs.end(); ++it) { char sit[128] = ""; sprintf(sit, "%d", (*it) + 1); s = s + "\t(line " + sit + ") " + tq.text_line(*it) + "\r\n"; } s = s + "\nenter word to look for, or q to quit: "; conn->send(s); }
void messageCallback(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time) { LOG_DEBUG << "---mesageCallback"; string str = buf->retrieveAllAsString(); printf("%s\n", str.c_str()); conn->send(str); }
void EchoServer::onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time){ string msg(buf->retrieveAllAsString()); LOG_INFO << conn->name() << " echo " << msg.size() << " bytes at " << time.toString(); conn->send(msg); }
void onMessage(const TcpConnectionPtr& conn, ByteBuffer *buf, Timestamp) { ++messagesRead_; bytesRead_ += buf->readableBytes(); bytesWritten_ += buf->readableBytes(); //printf("read : %s\n", buf->toString().c_str()); conn->send(buf); }
void add(const TcpConnectionPtr& conn) { audiences_.insert(conn); if (lastPubTime_.valid())//这样做,一有sub连上来,就发之前的消息给他 { conn->send(makeMessage()); } }
//----------------------------------------------------------------------------- // 描述: 接受了一个新的TCP连接 //----------------------------------------------------------------------------- void AppBusiness::onTcpConnected(const TcpConnectionPtr& connection) { logger().writeFmt("onTcpConnected (%s) (ConnCount: %d)", connection->getPeerAddr().getDisplayStr().c_str(), connection->getServerConnCount()); string msg = "Welcome to the simple echo server, type 'quit' to exit.\r\n"; connection->send(msg.c_str(), msg.length()); }
void sendMyTime() { if (clientConnection) { int64_t message[2] = { 0, 0 }; message[0] = Timestamp::now().microSecondsSinceEpoch(); clientConnection->send(message, sizeof message); } }
void ServerModule_Daytime::onTcpConnected(const TcpConnectionPtr& connection) { logger().writeFmt("onTcpConnected (%s) (ConnCount: %d)", connection->getPeerAddr().getDisplayStr().c_str(), connection->getServerConnCount()); string msg = DateTime::now().toDateTimeString() + "\n"; connection->send(msg.c_str(), msg.length()); }
void connectCallback( const TcpConnectionPtr& conn) { LOG_INFO << "-----------connectionCallback"; string msg = "a"; conn->send(msg); }
void onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp receiveTime) { if (buf->findCRLF()) { conn->send("No such user\r\n"); conn->shutdown(); } }
void sendDataByClient() { static int64_t i = 0; if (clientConnection) { Timestamp now = Timestamp::now(); char str[] = "hello world"; cout << "client send data : " << str << " at " << now.toString() <<"\n"; clientConnection->send(str, sizeof(str)); } }
void serverMessageCallback(const TcpConnectionPtr& conn, Buffer* buffer, kimgbo::Timestamp receiveTime) { int64_t message[2]; while (buffer->readableBytes() >= frameLen) { memcpy(message, buffer->peek(), frameLen); buffer->retrieve(frameLen); message[1] = receiveTime.microSecondsSinceEpoch(); conn->send(message, sizeof message); } }
void ServerModule_Chargen::onTcpConnected(const TcpConnectionPtr& connection) { logger().writeFmt("onTcpConnected (%s) (ConnCount: %d)", connection->getPeerAddr().getDisplayStr().c_str(), connection->getServerConnCount()); connection->setNoDelay(true); connection->recv(); connection->send(message_.c_str(), message_.length()); }
void QueryServer::runQuery(const string &s, const TcpConnectionPtr &conn) { string word = s; if(word.substr(word.size()-2, 2) == "\r\n") { word.erase(word.size()-1); word.erase(word.size()-1); } string res = final_.runLCS(word); conn->send(res + "\r\n"); }
//把计算任务和tcp回发做成一个函数,交给线程池 void EchoServer::compute(const std::string &word, const TcpConnectionPtr &conn) { string s = word; for(size_t ix = 0; ix != s.size(); ++ix) { if(isupper(s[ix])) s[ix] = tolower(s[ix]); else if(islower(s[ix]))\ s[ix] = toupper(s[ix]); } conn->send(s); }
void Session::onConnection(const TcpConnectionPtr& conn) { if(conn->connected()) { conn->setNoDelay(true); conn->send(owner_->message()); owner_->onConnect(); } else { owner_->onDisconnect(conn); } }
void onConnection(const TcpConnectionPtr& conn){ LOG_INFO << "FileServer - " << conn->peerAddress().toIpPort() << " -> " << conn->localAddress().toIpPort() << " is " << (conn->connected() ? "UP" : "DOWN"); if(conn->connected()){ LOG_INFO << "FileServer - Sending file " << g_file << " to " << conn->peerAddress().toIpPort(); conn->setHighWaterMarkCallback(onHighWaterMark, 64*1024); string fileContent = readFile(g_file); conn->send(fileContent); conn->shutdown(); LOG_INFO << "FileServer - done"; } }
//----------------------------------------------------------------------------- // 描述: TCP连接上的一个接收任务已完成 //----------------------------------------------------------------------------- void AppBusiness::onTcpRecvComplete(const TcpConnectionPtr& connection, void *packetBuffer, int packetSize, const Context& context) { logger().writeStr("onTcpRecvComplete"); string msg((char*)packetBuffer, packetSize); msg = trimString(msg); if (msg == "quit") connection->disconnect(); else connection->send((char*)packetBuffer, packetSize); logger().writeFmt("Received message: %s", msg.c_str()); }
void BaseSvr::onMessage(const TcpConnectionPtr& conn, Buffer* buf) { LOG_INFO << "accept msg from <" << conn->name() << ">"; string request(buf->peek(), buf->beginWrite()); LOG_INFO << "received msg from client<" << conn->peerAddress().IpAndPort() << "> : <" << request << ">"; conn->send(request); size_t len = 0; while((len = buf->readableBytes()) > 1) { // 本消息包除头部外剩余部分的长度 size_t packetLen = endian::networkToHost16(buf->peekInt16()); if(packetLen > len) {///< 缓冲区剩余空间反而大于消息包长度了 > conn->send("peek msg fail: packetLen > len of buffer\r\n"); conn->shutdown(); break; } if(false == protobufapi::checksum(buf->peek() + HEADER_LENGTH, packetLen)) {///< 校验结果不匹配 > conn->send("server check sum error. your msg is discard"); conn->shutdown(); break; } Buffer *pMsg = new Buffer(); pMsg->retrieveAll(); pMsg->append(buf->peek() + sizeof int16_t, sizeof int16_t + packetLen - TAIL_LENGTH); m_msgQueue.put(pMsg); buf->retrieve(packetLen + HEADER_LENGTH); } }
void publish( const string& content, ProtobufCodecLite& codec, Counters& counters) { PubSubMessage message = makeMessage(content); muduo::net::Buffer buf; codec.fillEmptyBuffer(&buf, message); for (auto audience : audiences_) { TcpConnectionPtr tcpConnection = audience.lock(); if (tcpConnection.get()) { tcpConnection->send(buf.peek(), buf.readableBytes()); counters.addOutBoundTraffic(buf.readableBytes()); counters.incrementOutBoundMessage(); } } }
void onConnection(const TcpConnectionPtr& conn) { LOG_TRACE << conn->localAddress().toIpPort() << " -> " << conn->peerAddress().toIpPort() << " is " << (conn->connected() ? "UP" : "DOWN"); if (conn->connected()) { conn->setTcpNoDelay(true); conn->send(message_); } else { loop_->quit(); } }
void onConnection(const TcpConnectionPtr& conn) { if (conn->connected()) { printf("onConnection(): tid=%d new connection [%s] from %s\n", CurrentThread::tid(), conn->name().c_str(), conn->peerAddress().toIpPort().c_str()); conn->send(message); //一连接就发送 } else { printf("onConnection(): tid=%d connection [%s] is down\n", CurrentThread::tid(), conn->name().c_str()); } }
void AppBusiness::onTcpConnected(const TcpConnectionPtr& connection) { const int MAX_CONN_COUNT = 3; logger().writeFmt("onTcpConnected (%s) (ConnCount: %d)", connection->getPeerAddr().getDisplayStr().c_str(), connection->getServerConnCount()); int connCount = connection->getServerConnCount(); if (connCount > MAX_CONN_COUNT) { logger().writeFmt("Too many connections. (ConnCount: %d)", connCount); connection->disconnect(); } else { string msg = "Welcome to the simple echo server, type 'quit' to exit.\r\n"; connection->send(msg.c_str(), msg.length()); } }
void HttpServer::onMessage(const TcpConnectionPtr& conn, ByteBuffer *buf, Timestamp receiveTime) { LOG_INFO("HttpServer::onConnection recv data [%d][%s]", conn->fd(), buf->toString().c_str()); HttpContext *context = zl::stl::any_cast<HttpContext>(conn->getMutableContext()); assert(context); if(!context->parseRequest(buf, receiveTime)) { conn->send("HTTP/1.1 400 Bad Request\r\n\r\n"); conn->send("HTTP/1.1 400 Bad Request\r\n\r\n"); conn->shutdown(); } if (context->gotAll()) { LOG_INFO("HttpServer::onMessage parse request over."); response(conn, context->request()); context->reset(); // process request and return response, then reset, for long-connection } }
void tcp_server::onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time) { muduo::string msg(buf->retrieveAllAsString()); std::string query = ""; for (muduo::string::iterator it = msg.begin(); it != msg.end(); ++it) query += *it; std::string::size_type pos_r = query.find(char(0x0A)); std::string::size_type pos_n = query.find(char(0x0D)); std::string::size_type pos = pos_r < pos_n ? pos_r : pos_n; std::string subquery; if (pos != std::string::npos) subquery = query.substr(0, pos); LOG_TRACE << "Received: " << subquery; string answer; if (mReadCallback) mReadCallback(subquery, answer); if (answer.length()) { unsigned int sourceSize = answer.size(); const char * source = answer.c_str(); unsigned long dsize = sourceSize + (sourceSize * 0.1f) + 16; char * destination = new char[dsize]; int result = compress2((unsigned char *) destination, &dsize, (const unsigned char *) source, sourceSize, Z_DEFAULT_COMPRESSION); if (result != Z_OK) LOG_ERROR<< "Compress error occured! Error code: " << result; answer = string(destination, dsize); answer.append("\r\n"); conn->send(answer); LOG_TRACE << "Replied " << answer.size() << " bytes : " << answer; } }
void HttpServer::response(const TcpConnectionPtr& conn, const HttpRequest& req) { const string& connection = req.getHeader("Connection"); bool close = connection == "close" || (req.version() == HTTP_VERSION_1_0 && connection != "Keep-Alive"); HttpResponse response(close); response.setStatusCode(HttpStatusOk); response.setServerName("MyHttpServer"); methodCallback(req, &response); // callback, for init response ByteBuffer buf; response.compileToBuffer(&buf); //printf("[%s]\n", buf.toString().c_str()); conn->send(&buf); LOG_INFO("HttpServer::response send data [%d]", conn->fd()); if (response.closeConnection()) { LOG_INFO("HttpServer::response close this[%d]", conn->fd()); conn->shutdown(); } }