unix网络编程2.7——高并发服务器(七)基于epoll&&reactor实现web_socket服务器
系列文章
阅读本文需要先阅读下面的文章:
unix网络编程1.1——TCP协议详解(一)
unix网络编程2.1——高并发服务器(一)基础——io与文件描述符、socket编程与单进程服务端客户端实现
unix网络编程2.2——高并发服务器(二)多进程与多线程实现
unix网络编程2.3——高并发服务器(三)多路IO复用之select
unix网络编程2.4——高并发服务器(四)epoll基础篇
unix网络编程2.5——高并发服务器(五)epoll进阶篇——基于epoll实现reactor
unix网络编程2.6——高并发服务器(六)基于epoll&&reactor实现http服务器
本文用ws代表wesocket缩写
ws协议: 1、握手 和 2、数据传输
- rfc文档走读(待补充)
握手与数据传输的不同
- 握手为了兼容http协议,采用的是类http协议的key : value的明文传输(字符格式)
- 数据传输的每一帧数据,则采用二进制形式的码流,基于tcp基础上做长连接(兼容tcp),解决粘包问题
tips:
自定义协议:
1.解决tcp粘包和分包(ws的数据帧格式就解决了1)
2.在1的基础上再去使用json/xml等格式
1、ws握手
ws的握手与tcp三次握手的关系
- tcp3次握手发生在传输层,用于建立连接
- ws的握手handshake基于tcp已经建立连接,客户端给服务端发送某字符,服务端回复,说明客户端与服务端已经可以通过ws通信
ws握手流程
- client发给服务器请求信息, 其中取出Sec-WebSocket-Key对应的value,记为 key = 8MwRzcen7uv2bHScmqL7qA==
GET / HTTP/1.1
Host: 192.168.239.128:8888
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
Upgrade: websocket
Origin: null
Sec-WebSocket-Version: 13
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Sec-WebSocket-Key: 8MwRzcen7uv2bHScmqL7qA==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
- client与server之间有一个全局的身份标识器: Globally Unique Identifier (GUID)
- GUID = 258EAFA5-E914-47DA-95CA-C5AB0DC85B11
- 令 key + GUID组成新的字符串 str = 8MwRzcen7uv2bHScmqL7qA==258EAFA5-E914-47DA-95CA-C5AB0DC85B11
- 利用hash算法和base64编码操作str,得到value, 作为server给client的响应值,标识握手完成
- sha = SHA-1(sta)
- value = base64-encode(sha)
- server给client回响应, value存在Sec-WebSocket-Accept对应的value中
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: value
2、数据传输
数据帧/包格式
数据包分为3部分
数据包长度
源码
server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <openssl/sha.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <assert.h>
#define BUFFER_LENGTH 1024
#define ACCEPT_KEY_LENGTH 64
#define MAX_EPOLL_EVENTS 1024
#define SERVER_PORT 8888
#define PORT_COUNT 1
#define GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
enum {
WS_HANDSHARK = 0,
WS_TRANSMISSION,
WS_END,
WS_STATUS_BUT
};
// 小端
typedef struct ws_ophdr {
unsigned char opcode: 4,
rsv3: 1,
rsv2: 1,
rsv1: 1,
fin: 1;
unsigned char pl_len: 7,
mask: 1;
} ws_ophdr;
typedef int NCALLBACK(int ,int, void*);
struct ntyevent {
int fd;
int events;
void *arg;
int (*callback)(int fd, int events, void *arg);
int status;
char buffer[BUFFER_LENGTH]; // request
int length;
//long last_active;
char wbuffer[BUFFER_LENGTH]; // response
int wlength;
char sec_accept[ACCEPT_KEY_LENGTH];
int ws_status; // WS_HANDSHARK -> WS_TRANMISSION -> WS_END
};
struct eventblock {
struct eventblock *next;
struct ntyevent *events;
};
struct ntyreactor {
int epfd;
int blkcnt;
struct eventblock *evblks;
};
int recv_cb(int fd, int events, void *arg);
int send_cb(int fd, int events, void *arg);
struct ntyevent *ntyreactor_idx(struct ntyreactor *reactor, int sockfd);
void nty_event_set(struct ntyevent *ev, int fd, NCALLBACK callback, void *arg) {
ev->fd = fd;
ev->callback = callback;
ev->events = 0;
ev->arg = arg;
//ev->last_active = time(NULL);
return ;
}
int nty_event_add(int epfd, int events, struct ntyevent *ev) {
struct epoll_event ep_ev = {0, {0}};
ep_ev.data.ptr = ev;
ep_ev.events = ev->events = events;
int op;
if (ev->status == 1) {
op = EPOLL_CTL_MOD;
} else {
op = EPOLL_CTL_ADD;
ev->status = 1;
}
if (epoll_ctl(epfd, op, ev->fd, &ep_ev) < 0) {
printf("event add failed [fd=%d], events[%d]\n", ev->fd, events);
return -1;
}
return 0;
}
int nty_event_del(int epfd, struct ntyevent *ev) {
struct epoll_event ep_ev = {0, {0}};
if (ev->status != 1) {
return -1;
}
ep_ev.data.ptr = ev;
ev->status = 0;
epoll_ctl(epfd, EPOLL_CTL_DEL, ev->fd, &ep_ev);
return 0;
}
int base64_encode(char *in_str, int in_len, char *out_str)
{
BIO *b64, *bio;
BUF_MEM *bptr = NULL;
size_t size = 0;
if (in_str == NULL || out_str == NULL)
return -1;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
BIO_write(bio, in_str, in_len);
BIO_flush(bio);
BIO_get_mem_ptr(bio, &bptr);
memcpy(out_str, bptr->data, bptr->length);
out_str[bptr->length-1] = '\0';
size = bptr->length;
BIO_free_all(bio);
return size;
}
int readline(char *allbuf, int idx, char *linebuf)
{
int len = strlen(allbuf);
for (; idx + 1 < len; idx++) {
if (allbuf[idx] == '\r' && allbuf[idx + 1] == '\n') {
return idx + 2;
} else {
*(linebuf++) = allbuf[idx];
}
}
return -1;
}
int handshark(struct ntyevent *ev)
{
int idx = 0;
char tmp[20] = "Sec-WebSocket-Key: ";
char sec_data[128] = {0};
char sec_accept[128] = {0};
do {
char linebuf[1024] = {0};
idx = readline(ev->buffer, idx, linebuf);
if (strstr(linebuf, tmp)) {
strcat(linebuf, GUID);
SHA1(linebuf + sizeof(tmp) - 1, strlen(linebuf + strlen(tmp)), sec_data);
base64_encode(sec_data, strlen(sec_data), sec_accept);
memset(ev->sec_accept, 0, ACCEPT_KEY_LENGTH);
memcpy(ev->sec_accept, sec_accept, ACCEPT_KEY_LENGTH);
}
} while (idx != -1 && ev->buffer[idx] != '\r' && ev->buffer[idx + 1] != '\n');
}
void umask(char *payload, int length, char *mask_key) {
int i = 0;
for (i = 0;i < length;i ++) {
payload[i] ^= mask_key[i%4];
}
}
int ws_transmission(struct ntyevent *ev)
{
// ev->buffer
ws_ophdr *hdr = (ws_ophdr *)ev->buffer;
if (hdr == NULL) return -1;
unsigned char *playload = NULL;
if (hdr->pl_len < 126) {
if (hdr->mask == 1) { // mask set 1
playload = ev->buffer + sizeof(ws_ophdr) + 4; // 6 payload length < 126
umask(playload, hdr->pl_len, ev->buffer + 2);
} else {
playload = ev->buffer + sizeof(ws_ophdr) + 2;
}
printf("playload = %s\n", playload);
} else if (hdr->pl_len == 126) {
} else if (hdr->pl_len == 127) {
} else {
assert(0);
}
}
int ws_request(struct ntyevent *ev)
{
if (ev->ws_status == WS_HANDSHARK) {
handshark(ev);
ev->ws_status = WS_TRANSMISSION;
} else if (ev->ws_status == WS_TRANSMISSION) {
ws_transmission(ev);
// 何时退出: ws 数据包格式,第一个BIT为FIN时,状态发生迁移
}
}
int ws_response(struct ntyevent *ev)
{
ev->wlength = sprintf(ev->wbuffer, "HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: %s\r\n\r\n", ev->sec_accept);
return ev->wlength;
}
// connection
int recv_cb(int fd, int events, void *arg) {
struct ntyreactor *reactor = (struct ntyreactor*)arg;
struct ntyevent *ev = ntyreactor_idx(reactor, fd);
if (ev == NULL) return -1;
int len = recv(fd, ev->buffer, BUFFER_LENGTH, 0);
nty_event_del(reactor->epfd, ev);
if (len > 0) {
ev->length = len;
ev->buffer[len] = '\0';
printf("recv [fd=%d]: [len=%d] %s\n", fd, ev->length, ev->buffer);
ws_request(ev); // decode
nty_event_set(ev, fd, send_cb, reactor);
nty_event_add(reactor->epfd, EPOLLOUT, ev);
} else if (len == 0) {
nty_event_del(reactor->epfd, ev);
printf("recv_cb --> disconnect\n");
close(ev->fd);
} else {
if (errno == EAGAIN && errno == EWOULDBLOCK) { //
} else if (errno == ECONNRESET) {
nty_event_del(reactor->epfd, ev);
close(ev->fd);
}
printf("recv[fd=%d] error[%d]:%s\n", fd, errno, strerror(errno));
}
return len;
}
int send_cb(int fd, int events, void *arg) {
struct ntyreactor *reactor = (struct ntyreactor*)arg;
struct ntyevent *ev = ntyreactor_idx(reactor, fd);
if (ev == NULL) return -1;
ws_response(ev);
int len = send(fd, ev->wbuffer, ev->wlength, 0);
if (len > 0) {
printf("send [fd=%d], [len=%d]: %s\n", fd, ev->wlength, ev->wbuffer);
nty_event_del(reactor->epfd, ev);
nty_event_set(ev, fd, recv_cb, reactor);
nty_event_add(reactor->epfd, EPOLLIN, ev);
} else {
nty_event_del(reactor->epfd, ev);
close(ev->fd);
printf("send[fd=%d] error %s\n", fd, strerror(errno));
}
return len;
}
int accept_cb(int fd, int events, void *arg) {
struct ntyreactor *reactor = (struct ntyreactor*)arg;
if (reactor == NULL) return -1;
struct sockaddr_in client_addr;
socklen_t len = sizeof(client_addr);
int clientfd;
if ((clientfd = accept(fd, (struct sockaddr*)&client_addr, &len)) == -1) {
if (errno != EAGAIN && errno != EINTR) {
}
printf("accept: %s\n", strerror(errno));
return -1;
}
int flag = 0;
if ((flag = fcntl(clientfd, F_SETFL, O_NONBLOCK)) < 0) {
printf("%s: fcntl nonblocking failed, %d\n", __func__, MAX_EPOLL_EVENTS);
return -1;
}
struct ntyevent *event = ntyreactor_idx(reactor, clientfd);
if (event == NULL) return -1;
nty_event_set(event, clientfd, recv_cb, reactor);
nty_event_add(reactor->epfd, EPOLLIN, event);
printf("new connect [%s:%d], pos[%d]\n",
inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), clientfd);
return 0;
}
int init_sock(short port) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
fcntl(fd, F_SETFL, O_NONBLOCK);
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
bind(fd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (listen(fd, 20) < 0) {
printf("listen failed : %s\n", strerror(errno));
return -1;
}
printf("listen server port : %d\n", port);
return fd;
}
int ntyreactor_alloc(struct ntyreactor *reactor) {
if (reactor == NULL) return -1;
if (reactor->evblks == NULL) return -1;
struct eventblock *blk = reactor->evblks;
while (blk->next != NULL) {
blk = blk->next;
}
struct ntyevent* evs = (struct ntyevent*)malloc((MAX_EPOLL_EVENTS) * sizeof(struct ntyevent));
if (evs == NULL) {
printf("ntyreactor_alloc ntyevent failed\n");
return -2;
}
memset(evs, 0, (MAX_EPOLL_EVENTS) * sizeof(struct ntyevent));
struct eventblock *block = malloc(sizeof(struct eventblock));
if (block == NULL) {
printf("ntyreactor_alloc eventblock failed\n");
return -3;
}
block->events = evs;
block->next = NULL;
blk->next = block;
reactor->blkcnt ++;
return 0;
}
struct ntyevent *ntyreactor_idx(struct ntyreactor *reactor, int sockfd) {
if (reactor == NULL) return NULL;
if (reactor->evblks == NULL) return NULL;
int blkidx = sockfd / MAX_EPOLL_EVENTS;
while (blkidx >= reactor->blkcnt) {
ntyreactor_alloc(reactor);
}
int i = 0;
struct eventblock *blk = reactor->evblks;
while (i++ != blkidx && blk != NULL) {
blk = blk->next;
}
return &blk->events[sockfd % MAX_EPOLL_EVENTS];
}
int ntyreactor_init(struct ntyreactor *reactor) {
if (reactor == NULL) return -1;
memset(reactor, 0, sizeof(struct ntyreactor));
reactor->epfd = epoll_create(1);
if (reactor->epfd <= 0) {
printf("create epfd in %s err %s\n", __func__, strerror(errno));
return -2;
}
struct ntyevent* evs = (struct ntyevent*)malloc((MAX_EPOLL_EVENTS) * sizeof(struct ntyevent));
if (evs == NULL) {
printf("create epfd in %s err %s\n", __func__, strerror(errno));
close(reactor->epfd);
return -3;
}
memset(evs, 0, (MAX_EPOLL_EVENTS) * sizeof(struct ntyevent));
struct eventblock *block = malloc(sizeof(struct eventblock));
if (block == NULL) {
free(evs);
close(reactor->epfd);
return -3;
}
block->events = evs;
block->next = NULL;
reactor->evblks = block;
reactor->blkcnt = 1;
return 0;
}
int ntyreactor_destory(struct ntyreactor *reactor) {
close(reactor->epfd);
struct eventblock *blk = reactor->evblks;
struct eventblock *blk_next;
while (blk != NULL) {
blk_next = blk->next;
free(blk->events);
free(blk);
blk = blk_next;
}
return 0;
}
int ntyreactor_addlistener(struct ntyreactor *reactor, int sockfd, NCALLBACK *acceptor) {
if (reactor == NULL) return -1;
if (reactor->evblks == NULL) return -1;
struct ntyevent *event = ntyreactor_idx(reactor, sockfd);
if (event == NULL) return -1;
nty_event_set(event, sockfd, acceptor, reactor);
nty_event_add(reactor->epfd, EPOLLIN, event);
return 0;
}
int ntyreactor_run(struct ntyreactor *reactor) {
if (reactor == NULL) return -1;
if (reactor->epfd < 0) return -1;
if (reactor->evblks == NULL) return -1;
struct epoll_event events[MAX_EPOLL_EVENTS+1];
int checkpos = 0, i;
while (1) {
int nready = epoll_wait(reactor->epfd, events, MAX_EPOLL_EVENTS, 1000);
if (nready < 0) {
printf("epoll_wait error, exit\n");
continue;
}
for (i = 0;i < nready;i ++) {
struct ntyevent *ev = (struct ntyevent*)events[i].data.ptr;
if ((events[i].events & EPOLLIN) && (ev->events & EPOLLIN)) {
ev->callback(ev->fd, events[i].events, ev->arg);
}
if ((events[i].events & EPOLLOUT) && (ev->events & EPOLLOUT)) {
ev->callback(ev->fd, events[i].events, ev->arg);
}
}
}
}
int main(int argc, char *argv[]) {
struct ntyreactor *reactor = (struct ntyreactor*)malloc(sizeof(struct ntyreactor));
ntyreactor_init(reactor);
unsigned short port = SERVER_PORT;
if (argc == 2) {
port = atoi(argv[1]);
}
int i = 0;
int sockfds[PORT_COUNT] = {0};
for (i = 0;i < PORT_COUNT;i ++) {
sockfds[i] = init_sock(port+i);
ntyreactor_addlistener(reactor, sockfds[i], accept_cb);
}
ntyreactor_run(reactor);
ntyreactor_destory(reactor);
for (i = 0;i < PORT_COUNT;i ++) {
close(sockfds[i]);
}
free(reactor);
return 0;
}
状态迁移
- 状态机: 握手阶段 -> 数据传输阶段 -> 关闭
websocket的好处
- http请求头请求体数据多,占用带宽资源多
- http不能实现服务端主动推送数据给客户端(比分实时更新,扫码推送信息)
- 在TCP上实现帧机制,来回到IP包机制,而没有长度限制