gpt4 book ai didi

c++ - 在这个 C++ TCP 客户端中,我在哪里设置 TCP_NODELAY?

转载 作者:行者123 更新时间:2023-11-30 19:15:43 26 4
gpt4 key购买 nike

在此 C++ TCP 客户端中,我在哪里设置 TCP_NODELAY

    // Client socket descriptor which is just integer number used to access a socket
int sock_descriptor;
struct sockaddr_in serv_addr;

// Structure from netdb.h file used for determining host name from local host's ip address
struct hostent *server;

// Create socket of domain - Internet (IP) address, type - Stream based (TCP) and protocol unspecified
// since it is only useful when underlying stack allows more than one protocol and we are choosing one.
// 0 means choose the default protocol.
sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);

if (sock_descriptor < 0)
printf("Failed creating socket\n");

bzero((char *) &serv_addr, sizeof(serv_addr));

server = gethostbyname(host);

if (server == NULL) {
printf("Failed finding server name\n");
return -1;
}

serv_addr.sin_family = AF_INET;

memcpy((char *) &(serv_addr.sin_addr.s_addr), (char *) (server->h_addr), server->h_length);

// 16 bit port number on which server listens
// The function htons (host to network short) ensures that an integer is
// interpreted correctly (whether little endian or big endian) even if client and
// server have different architectures
serv_addr.sin_port = htons(port);

if (connect(sock_descriptor, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
printf("Failed to connect to server\n");
return -1;
} else
printf("Connected successfully - Please enter string\n");

最佳答案

TCP_NODELAY 是给setsockopt 系统调用的选项:

#include <netinet/tcp.h>

int yes = 1;
int result = setsockopt(sock,
IPPROTO_TCP,
TCP_NODELAY,
(char *) &yes,
sizeof(int)); // 1 - on, 0 - off
if (result < 0)
// handle the error

这是为了关闭 Nagle 缓冲。仅当您确实知道自己在做什么时才应打开此选项。

关于c++ - 在这个 C++ TCP 客户端中,我在哪里设置 TCP_NODELAY?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31997648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com