Linux Socket Option : TCP_NODELAY
int init_socket(mqtt_broker_handle_t* broker, const char* hostname, short port, int keepalive)
{
int flag = 1;
// Create the socket
if((socket_id = socket(PF_INET, SOCK_STREAM, 0)) < 0)
return -1;
// Disable Nagle Algorithm
if (setsockopt(socket_id, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(flag)) < 0)
return -2;
struct sockaddr_in socket_address;
// Create the stuff we need to connect
socket_address.sin_family = AF_INET;
socket_address.sin_port = htons(port);
socket_address.sin_addr.s_addr = inet_addr(hostname);
// Connect the socket
if((connect(socket_id, (struct sockaddr*)&socket_address, sizeof(socket_address))) < 0)
return -1;
// MQTT stuffs
mqtt_set_alive(broker, keepalive);
broker->socket_info = (void*)&socket_id;
broker->send = send_packet;
return 0;
}
Disable Nagle Algorithm:
為了提升TCP傳送效率, 不要送一點資料就送出一個TCP/IP封包, 若只送1 byte , 先不看MAC層header 光TCP+IP Header 就有40byte了, overhead 太大, 所以Nagle 這個人, 就提一個方法, 累積一定的大小才送..
if there is new data to send if the window size >= MSS and available data is >= MSS send complete MSS segment now else if there is unconfirmed data still in the pipe enqueue data in the buffer until an acknowledge is received else send data immediately end if end if end if