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 &