| 
                         这里我们的http协议使用的是12345端口号而不是默认的80端口。如何侦听12345端口,这个是非常基础的知识了,这里就不介绍了。当我们收到数据以后: 
- 1void HttpSession::OnRead(const std::shared_ptr<TcpConnection>& conn, Buffer* pBuffer, Timestamp receivTime) 
 -  2{ 
 -  3    //LOG_INFO << "Recv a http request from " << conn->peerAddress().toIpPort(); 
 -  4 
 -  5    string inbuf; 
 -  6    //先把所有数据都取出来 
 -  7    inbuf.append(pBuffer->peek(), pBuffer->readableBytes()); 
 -  8    //因为一个http包头的数据至少rnrn,所以大于4个字符 
 -  9    //小于等于4个字符,说明数据未收完,退出,等待网络底层接着收取 
 - 10    if (inbuf.length() <= 4) 
 - 11        return; 
 - 12 
 - 13    //我们收到的GET请求数据包一般格式如下: 
 - 14    /* 
 - 15    GET /register.do?p={%22username%22:%20%2213917043329%22,%20%22nickname%22:%20%22balloon%22,%20%22password%22:%20%22123%22} HTTP/1.1rn 
 - 16    Host: 120.55.94.78:12345rn 
 - 17    Connection: keep-alivern 
 - 18    Upgrade-Insecure-Requests: 1rn 
 - 19    User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36rn 
 - 20    Accept-Encoding: gzip, deflatern 
 - 21    Accept-Language: zh-CN, zh; q=0.9, en; q=0.8rn 
 - 22    rn 
 - 23     */ 
 - 24    //检查是否以rnrn结束,如果不是说明包头不完整,退出 
 - 25    string end = inbuf.substr(inbuf.length() - 4); 
 - 26    if (end != "rnrn") 
 - 27        return; 
 - 28 
 - 29    //以rn分割每一行 
 - 30    std::vector<string> lines; 
 - 31    StringUtil::Split(inbuf, lines, "rn"); 
 - 32    if (lines.size() < 1 || lines[0].empty()) 
 - 33    { 
 - 34        conn->forceClose(); 
 - 35        return; 
 - 36    } 
 - 37 
 - 38    std::vector<string> chunk; 
 - 39    StringUtil::Split(lines[0], chunk, " "); 
 - 40    //chunk中至少有三个字符串:GET+url+HTTP版本号 
 - 41    if (chunk.size() < 3) 
 - 42    { 
 - 43        conn->forceClose(); 
 - 44        return; 
 - 45    } 
 - 46 
 - 47    LOG_INFO << "url: " << chunk[1] << " from " << conn->peerAddress().toIpPort(); 
 - 48    //inbuf = /register.do?p={%22username%22:%20%2213917043329%22,%20%22nickname%22:%20%22balloon%22,%20%22password%22:%20%22123%22} 
 - 49    std::vector<string> part; 
 - 50    //通过?分割成前后两端,前面是url,后面是参数 
 - 51    StringUtil::Split(chunk[1], part, "?"); 
 - 52    //chunk中至少有三个字符串:GET+url+HTTP版本号 
 - 53    if (part.size() < 2) 
 - 54    { 
 - 55        conn->forceClose(); 
 - 56        return; 
 - 57    } 
 - 58 
 - 59    string url = part[0]; 
 - 60    string param = part[1].substr(2); 
 - 61 
 - 62    if (!Process(conn, url, param)) 
 - 63    { 
 - 64        LOG_ERROR << "handle http request error, from:" << conn->peerAddress().toIpPort() << ", request: " << pBuffer->retrieveAllAsString(); 
 - 65    } 
 - 66 
 - 67    //短连接,处理完关闭连接 
 - 68    conn->forceClose(); 
 - 69} 
 
                          (编辑:滁州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |