Socket 与 Websocket通信交互 Linux/C++/epoll网络模型

                 Socket 与 Websocket通信交互 Linux/C++/epoll网络模型

 简要:Websocket是基于http协议实现的,而Socket是基于TCP/IP协议实现的。所以要想使Socket与Websocket进行数据交互,就必须在网络层手动解析http协议,大致分为两个步骤:握手连接 拆分协议帧。本实例使用Linux网络库,C++开发语言,epoll网络模型(不熟悉的童鞋可以百度,两者网络数据通信和epoll网络模型没有联系)

示例代码:

1.main测试cpp

#include <stdio.h>
#include <sys/epoll.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/resource.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>

#include <map>
#include <sstream>

#include "define.h"
#include "SHA1.h"
#include "base64.hpp"

#define MAXBUF 1024
#define MAXEPOLLSIZE 10000

static int ConnType[MAXBUF] = {unknow};

// 解析http数据头信息
int fetch_http_info(std::map<std::string, std::string>& header_map, const std::string& src)
{
    std::string end_char = "\r\n\r\n";
    std::string::size_type pos = src.find(end_char);
    if (std::string::npos == pos)
    {
        return 0;
    }

    std::istringstream s(src);
    std::string line;

    while (std::getline(s, line))
    {
        if (!line.empty() &&
            line[line.size() - 1] == '\r')
        {
            line.erase(line.end() - 1);
        }

         std::string::size_type end = line.find(": ", 0);
        if (end != std::string::npos)
        {
            std::string key = line.substr(0, end);
            std::string value = line.substr(end + 2);
            header_map[key] = value;
        }
    }

    return int(pos + end_char.size());
};

//解析数据
unsigned char * analyData(unsigned char * buf, unsigned long * bufLen)
{
    char fin, maskFlag,masks[4];
    unsigned char * payloadData;
    char temp[8];
    unsigned long n, payloadLen=0;
    unsigned int i=0;


    if (*bufLen < 2)
    {
        return NULL;
    }

    fin = (buf[0] & 0x80) == 0x80; // 1bit,1表示最后一帧
    if (!fin)
    {
        return NULL;// 超过一帧暂不处理
    }

    maskFlag = (buf[1] & 0x80) == 0x80; // 是否包含掩码
    if (!maskFlag)
    {
        return NULL;// 不包含掩码的暂不处理
    }

    payloadLen &
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值