websocket协议
1: websocket是基于TCP的一种协议,是H5的一种传输协议;
2: websocket连接协议;
3: websocket 发送数据协议;
4: websocket 接受数据协议;
5: websocket 关闭协议;
websocket连接协议
1:客户端向服务器发送http报文,服务器处理后回客户端连接报文;
2: 客户端发过来的报文:
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
3: 服务器回应客户端报文:
:key+migic , SHA-1 加密, base-64 加密
key=”来自客户端的随机”, migic = “258EAFA5-E914-47DA-95CA-C5AB0DC85B11”;
static char *wb_accept = “HTTP/1.1 101 Switching Protocols\r\n” \
“Upgrade:websocket\r\n” \
“Connection: Upgrade\r\n” \
“Sec-WebSocket-Accept: %s\r\n” \
“WebSocket-Protocol:chat\r\n\r\n”;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "uv.h"
#include "./../3rd/http_parser/http_parser.h"
#include "./../3rd/crypto/sha1.h"
#include "./../3rd/crypto/base64_encoder.h"
struct ws_context{
int is_shake_hand;//是否已经握手
char* data; //读取数据的buf
};
static uv_loop_t* loop = NULL;//创建对象
static uv_tcp_t l_server; //监听句柄
static void uv_alloc_buf(uv_handle_t* handle,
size_t suggested_size,
uv_buf_t* buf){
struct ws_context* wc = handle->data;
if (wc->data != NULL){
free(wc->data);
wc->data = NULL;
}
buf->base = malloc(suggested_size+1);
buf->len = suggested_size;
wc-> data = buf->base;
}
static void on_close(uv_handle_t* handle){
printf("close client \n");
if (handle->data){
struct ws_context* wc = handle->data;
free(wc->data);
wc->data = NULL;
free(wc);
handle->data = NULL;
}
free(handle);
}
static