示例#1
0
 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;
         }
     }
 }
示例#2
0
        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;
        }
示例#3
0
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: ");

}
示例#4
0
文件: zgw.cpp 项目: zhangnian/zgw
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);
}
示例#5
0
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);
}
示例#6
0
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);
}
示例#7
0
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);
}
示例#8
0
 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);
 }
示例#9
0
文件: hub.cpp 项目: 1suming/msmuduo
	void add(const TcpConnectionPtr& conn)
	{
		audiences_.insert(conn);
		if (lastPubTime_.valid())//这样做,一有sub连上来,就发之前的消息给他
		{
			conn->send(makeMessage());
		}
	}
示例#10
0
//-----------------------------------------------------------------------------
// 描述: 接受了一个新的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());
}
示例#11
0
void sendMyTime()
{
	if (clientConnection)
  {
    int64_t message[2] = { 0, 0 };
    message[0] = Timestamp::now().microSecondsSinceEpoch();
    clientConnection->send(message, sizeof message);
  }
}
示例#12
0
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());
}
示例#13
0
void connectCallback( const TcpConnectionPtr& conn)
{
	LOG_INFO << "-----------connectionCallback";
	string msg = "a";

	conn->send(msg);
 

}
示例#14
0
void onMessage(const TcpConnectionPtr& conn,
                Buffer* buf,
                Timestamp receiveTime)
{
    if (buf->findCRLF())
    {
        conn->send("No such user\r\n");
        conn->shutdown();
    }
}
示例#15
0
 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));
     }
 }
示例#16
0
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);
  }
}
示例#17
0
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());
}
示例#18
0
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");
}
示例#19
0
//把计算任务和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);
}
示例#20
0
void Session::onConnection(const TcpConnectionPtr& conn)
{
    if(conn->connected())
    {
        conn->setNoDelay(true);
        conn->send(owner_->message());
        owner_->onConnect();
    }
    else
    {
        owner_->onDisconnect(conn);
    }
}
示例#21
0
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";
    }
}
示例#22
0
//-----------------------------------------------------------------------------
// 描述: 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());
}
示例#23
0
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);
    }
}
示例#24
0
 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();
         }
     }
 }
示例#25
0
	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());
	}
}
示例#27
0
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());
    }
}
示例#28
0
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
     }
}
示例#29
0
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;
	}
}
示例#30
0
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();
    }
}