天蓬老师2017-04-17 13:02:273楼
/*
* Packs up the buf and write to socket in non-blocking way
* If all data is writen, return 1
* If only part of data is writen, return 0, to be continue next time
* If error occurs, return -1
*
* Note, if j_socket_write() returns 0, then you can call it with NULL in buf next time, until all data is writen
*/
int j_socket_write(JSocket * jsock, const void *buf, guint32 count)
{
guint32 size = j_socket_wdata_length(jsock);
if (size == 0) {
/* new data to write */
if (buf == NULL) {
return 1; /* no data? must be a mistake */
}
gchar *len = pack_length4(count);
j_socket_wdata_append(jsock, len, 4);
j_socket_wdata_append(jsock, buf, count);
g_free(len);
size = j_socket_wdata_length(jsock);
}
gint n;
count = size>4096?4096:size;
while(size>0){ /* writes segmentation */
n = j_socket_write_raw(jsock, j_socket_wdata(jsock), count);
if(n<0){
if(errno==EAGAIN){
return 0;
}
return -1; /* It's a real error */
}
j_socket_wdata_pop(jsock,n);
size = j_socket_wdata_length(jsock);
count = size>4096?4096:size;
}
return 1;
}
@我是宅男小何 刚好提醒了我,其实就算整块数据很大,也不一定要调用一次write就全部写入。
上面代码,将超过4096的数据分片发送,如果阻塞,则返回等待下一次调用。
这段代码还没有测试过,基本这个逻辑