| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- #include "sockio.h"
- // get char from client socket
- int sgetc(int clnt_sock, struct buffer *recv_buf)
- {
- if (recv_buf->ptr == recv_buf->len)
- {
- ssize_t n = read(clnt_sock, recv_buf->buf, BUF_SIZE);
- if (n == -1)
- {
- return -1;
- }
- if (n == 0) // avoid confusion with '\0'
- {
- return -2;
- }
- recv_buf->ptr = 0;
- recv_buf->len = n;
- }
- return (uint8_t)recv_buf->buf[recv_buf->ptr++]; // avoid confusion with '\xff'
- }
- // get line from client socket
- int sgetline(int clnt_sock, struct buffer *recv_buf, struct buffer *line_buf)
- {
- int cr = 0;
- for (line_buf->len = 0;;)
- {
- int c = sgetc(clnt_sock, recv_buf);
- if (c < 0)
- {
- return c;
- }
- line_buf->buf[line_buf->len++] = c;
- if (c == '\r')
- {
- cr = 1;
- }
- else if (c == '\n' && cr)
- {
- break;
- }
- else
- {
- cr = 0;
- }
- }
- line_buf->buf[line_buf->len] = '\0';
- return line_buf->len;
- }
- // flush send buffer
- int sflush(int clnt_sock, struct buffer *send_buf)
- {
- uint16_t len = send_buf->len;
- for (; send_buf->len;)
- {
- ssize_t n = write(clnt_sock, send_buf->buf + len - send_buf->len, send_buf->len);
- if (n == -1)
- {
- return -1;
- }
- send_buf->len -= n;
- }
- return len;
- }
- // put char to client socket
- int sputc(int clnt_sock, struct buffer *send_buf, char c)
- {
- if (send_buf->len == BUF_SIZE && sflush(clnt_sock, send_buf) == -1)
- {
- return -1;
- }
- send_buf->buf[send_buf->len++] = c;
- return (uint8_t)c; // avoid confusion with '\xff'
- }
- // put line to client socket
- int sputline(int clnt_sock, struct buffer *send_buf, struct buffer *line_buf)
- {
- for (char *s = line_buf->buf; s < line_buf->buf + line_buf->len; s++)
- {
- int c = sputc(clnt_sock, send_buf, *s);
- if (c == -1)
- {
- return -1;
- }
- }
- return line_buf->len;
- }
|