如何在socket编程中发送长度大于缓冲区的消息? [英] How to send messages with larger length than the buffer in socket programming?

查看:1157
本文介绍了如何在socket编程中发送长度大于缓冲区的消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C ++开发一个使用Winsock的应用程序。我有一个200字节长度的字符数组,用于通过套接字发送字符串。

I'm developing an application using Winsock in C++. I have a 200-byte-length char array for sending strings over the socket.

我的问题是发送大于char数组的消息,所以我决定发送它们在多个块,但我不知道如何做。

My problem is when sending messages which are larger than the char array, so I decided to send them in multiple chunks but I have no idea how to do it.

对于发送和接收数据,我使用常规 send () recv()函数:

For sending and receiving the data, I'm using the regular send() and recv() functions:

recv(client, buffer, 200, NULL);
send(client, buffer, 200, NULL);

更新

我有一个结构:

struct Pack
{
    unsigned int senderId;
    char str[200];
}


$ b $ c>到char数组。

before sending I convert the struct to char array.

Pack pk;
strcpy_s(pk.str, 200, "Some text to send.\0");
pk.senderId = 1 // user id
char *buffer = (char*)pk;

如果字符串大小大于200,则strcpy_s()崩溃。

If the string size if larger than 200 the strcpy_s() crashes.

推荐答案

您可以在 Beej的网络编程指南

7.3。处理部分send()s


记住上面关于send()的部分,当我说
send()可能不会发送你要求的所有字节?也就是说,你想要
它发送512字节,但它返回412.
剩下的100个字节发生了什么?

Remember back in the section about send(), above, when I said that send() might not send all the bytes you asked it to? That is, you want it to send 512 bytes, but it returns 412. What happened to the remaining 100 bytes?

'仍然在你的小缓冲区等待被发出。由于
的情况超出了你的控制,内核决定不发送
所有的数据在一个块,现在,我的朋友,这取决于你
获取数据在那里。

Well, they're still in your little buffer waiting to be sent out. Due to circumstances beyond your control, the kernel decided not to send all the data out in one chunk, and now, my friend, it's up to you to get the data out there.

您也可以这样写一个函数:

You could write a function like this to do it, too:



int sendall(int s, char *buf, int *len)
{
    int total = 0;        // how many bytes we've sent
    int bytesleft = *len; // how many we have left to send
    int n;

    while(total < *len) {
        n = send(s, buf+total, bytesleft, 0);
        if (n == -1) { break; }
        total += n;
        bytesleft -= n;
    }

    *len = total; // return number actually sent here

    return n==-1?-1:0; // return -1 onm failure, 0 on success
} 

by @alk,用 ssize_t 替换所有 int - send )

As pointed out by @alk, replace all those ints with ssize_t - The type returned by send()

这篇关于如何在socket编程中发送长度大于缓冲区的消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆