gpt4 book ai didi

c++ - 关于数据包和缓冲区大小的 TCP 套接字编程

转载 作者:可可西里 更新时间:2023-11-01 02:35:58 24 4
gpt4 key购买 nike

我知道在 TCP 中没有数据包的概念,因为它是一个流套接字,那么例如,如果我有一个 2000 字节的数据包,比如 2000 'a',并且我的默认缓冲区大小是 1024,那么它是应该发送两次并接收两次?

所以对于 send() 函数,

iResult = send(s, sendbuf, packet_size, 0);

第二个参数应该填什么?分配了 1024 字节的发送缓冲区字符指针或分配了 2000 字节的数据包字符指针,它会自动为我处理?

对于 recv() 阻塞函数,我应该将缓冲区字符指针指向第二个参数还是数据包参数?

对于header,我的 friend 建议我添加4个字节的header来存储数据包信息,例如。数据包的序列号和大小,如何实现?谢谢

@Giorgi,谢谢!我还想问,如果我不做部分写入处理并且 while 循环中的发送速率非常快(没有 sleep ),那么服务器端会不会出错/丢失?对于 recv()

SOCKET newsfd;
bind(s, (struct sockaddr *)ReceiverSocket, sizeof(struct sockaddr_in));
if (strcmp(protocol, "tcp") == 0 || strcmp(protocol, "TCP") == 0){
listen(s, 1);
newsfd = accept(s, 0, 0);
}

//*** Create Update Display Thread
std::thread th(Function_packet_transmission_display, update_interval, (char*) "recv");

//*** Receive Data//*** Set Jitter
long time_old = 0, time_new = 0, time_start = 0;
long float jitter_new = 0, jitter_old = 0;
long long temp_accubyte = 0, temp_pktnum = 0; //testing
char *recvbuf = new char[buffer_size];
long long next_seq_num = 1; int retVal;
do{

if (strcmp(protocol, "tcp") == 0 || strcmp(protocol, "TCP") == 0){
retVal = recv(newsfd, recvbuf, packet_size, 0);
if ((retVal == SOCKET_ERROR) || (retVal == 0)){
printf("\nreturn fail code:%i\n", WSAGetLastError());
closesocket(s);
WSACleanup();
lck.lock();
Ended = true;
lck.unlock();
return 0;
}
}
else if (strcmp(protocol, "udp") == 0 || strcmp(protocol, "UDP") == 0){
int fromlen = (int)sizeof(struct sockaddr_in);
retVal = recvfrom(s, recvbuf, packet_size, 0, (struct sockaddr *)ReceiverSocket, &fromlen);
}
//testing
temp_accubyte += retVal;
temp_pktnum++;//TEST
//printf("\racc: %lld %lld - ", temp_accubyte, temp_pktnum);
//if (temp_pktnum==100000) printf("\nReach 100000\n", temp_accubyte, temp_pktnum);

if (timer == NULL){
timer = new ES_FlashTimer();
}

最佳答案

If i have a packet of 2000 bytes, say 2000 'a',

你不知道。您有一条 2000 字节的消息

and my default buffer size is 1024

不太可能。它至少是 8192,可能是数千 K。

then it is supposed to send twice

至少。

and received twice?

至少。

for the second parameter, what should i put?

您要发送的消息的大小:在本例中为 2000。

sending buffer character pointer with 1024 bytes mallocated

没有。

or a packet character pointer with 2000 bytes and it will handle it for me automatically ?

是的。

and for the recv() blocking function, i should put the buffer character pointer to the second parameter or the packet one?

我无法弄清楚这一点,但你应该接收到尽可能大的缓冲区并循环直到你拥有完整的消息。

and for the header, my friend suggested me to add header of 4 bytes to store the packet information, eg. sequence number and size of packet, how can it be implemented!

您实际上不需要序列号,但消息大小是个好主意。只需将其粘贴在消息的前面即可。不清楚这里的问题是什么。

关于c++ - 关于数据包和缓冲区大小的 TCP 套接字编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33399909/

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