- int mg_write(struct mg_connection *conn, const void *buf, size_t len)
将buf指向的缓存中长度为len的数据发送到conn中,返回真正发送的数据大小。
int mg_write(struct mg_connection *conn, const void *buf, size_t len)
{
time_t now;
int64_t n, total, allowed;
if (conn->throttle > 0) {
if ((now = time(NULL)) != conn->last_throttle_time) {
conn->last_throttle_time = now;
conn->last_throttle_bytes = 0;
}
allowed = conn->throttle - conn->last_throttle_bytes;
if (allowed > (int64_t) len) {
allowed = len;
}
if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
(int64_t) allowed)) == allowed) {
buf = (char *) buf + total;
conn->last_throttle_bytes += total;
while (total < (int64_t) len && conn->ctx->stop_flag == 0) {
allowed = conn->throttle > (int64_t) len - total ?
(int64_t) len - total : conn->throttle;
if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
(int64_t) allowed)) != allowed) {
break;
}
sleep(1);
conn->last_throttle_bytes = allowed;
conn->last_throttle_time = time(NULL);
buf = (char *) buf + n;
total += n;
}
}
} else {
total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
(int64_t) len);
}
return (int) total;
}
- static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int64_t len)
将buf中len大小的数据发送到IO连接通道中,文件描述符,socket或者ssl socket,返回真正发送的数据量。
/* Write data to the IO channel - opened file descriptor, socket or SSL
descriptor. Return number of bytes written. */
static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int64_t len)
{
int64_t sent;
int n, k;
(void) ssl;
sent = 0;
while (sent < len) {
k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
#ifndef NO_SSL
if (ssl != NULL) {
n = SSL_write(ssl, buf + sent, k);
} else
#endif
if (fp != NULL) {
n = (int) fwrite(buf + sent, 1, (size_t) k, fp);
if (ferror(fp))
n = -1;
} else {
n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);
}
if (n <= 0)
break;
sent += n;
}
return sent;
}