89 lines
2 KiB
C
89 lines
2 KiB
C
#include "websock.h"
|
|
|
|
sat_websock_ptr sat_websock_alloc(void) {
|
|
sat_websock_ptr websock = malloc(sizeof(sat_websock));
|
|
memset(websock, 0, sizeof(sat_websock));
|
|
return websock;
|
|
}
|
|
|
|
void sat_websock_free(sat_websock_ptr ws) {
|
|
if(ws == NULL) return;
|
|
|
|
if(ws->closeInfo != NULL)
|
|
free(ws->closeInfo);
|
|
|
|
if(ws->buffer != NULL)
|
|
free(ws->buffer);
|
|
|
|
free(ws);
|
|
}
|
|
|
|
void sat_websock_init(sat_websock_ptr ws, sat_sock_ptr sock) {
|
|
ws->sock = sock;
|
|
ws->buffer = sat_buffer_alloc();
|
|
}
|
|
|
|
void sat_websock_tidy(sat_websock_ptr ws) {
|
|
sat_buffer_tidy(ws->buffer);
|
|
}
|
|
|
|
void sat_websock_close(sat_websock_ptr ws, int closeCode, char *closeReason) {
|
|
// send close frame
|
|
|
|
// should the sock be nuked right away?
|
|
sat_sock_close(ws->sock);
|
|
}
|
|
|
|
bool sat_websock_is_closed(sat_websock_ptr ws) {
|
|
return ws != NULL && ws->closeInfo == NULL;
|
|
}
|
|
|
|
int sat_websock_buffer(sat_websock_ptr ws, size_t want) {
|
|
size_t total = sat_buffer_available(ws->buffer);
|
|
if(total > want)
|
|
return total;
|
|
|
|
want -= total;
|
|
|
|
int read;
|
|
char buffer[1024] = {0};
|
|
while(total < want) {
|
|
if(sat_sock_select(ws->sock, 2) > 0) {
|
|
read = sat_sock_recv(ws->sock, (uint8_t*)buffer, 1024);
|
|
if(read == -1)
|
|
return read;
|
|
|
|
total += read;
|
|
}
|
|
}
|
|
|
|
return total;
|
|
}
|
|
|
|
int sat_websock_recv(sat_websock_ptr ws, uint8_t *buffer, size_t size) {
|
|
size_t buffered = sat_buffer_available(ws->buffer);
|
|
if(buffered >= size)
|
|
return sat_buffer_read(ws->buffer, (char*)buffer, size);
|
|
|
|
size -= buffered;
|
|
|
|
size_t total = 0;
|
|
int read;
|
|
while(total < size) {
|
|
if(sat_sock_select(ws->sock, 2) > 0) {
|
|
read = sat_sock_recv(ws->sock, buffer, size);
|
|
if(read == -1)
|
|
return read;
|
|
|
|
buffer += read;
|
|
total += read;
|
|
}
|
|
}
|
|
|
|
return total;
|
|
}
|
|
|
|
int sat_websock_send(sat_websock_ptr ws, uint8_t *buffer, size_t count) {
|
|
return sat_sock_send(ws->sock, buffer, count);
|
|
}
|