从 TCP 套接字接收完整消息

发布于 2024-09-19 08:22:23 字数 600 浏览 2 评论 0原文

我从 TCP 套接字连接读取数据,但服务器不时向我发送 \0 (这将标记消息的结束)。因此,我没有收到消息的其余部分。

我是这样读的:

uint8_t buf[tcpBufferSize];
unsigned int len = 0;

len = [inputStream read:buf maxLength:tcpBufferSize];

if(len > 0) {
    NSMutableData* data=[[NSMutableData alloc] initWithLength:0];
    [data appendBytes: (const void *)buf length:len];
    NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    //here s will be only the part before the \0

    [s release];
    [data release];
}

例如,如果服务器发送 abc\0de y 将只会得到 abc,因为 \0 标记结束。

我怎样才能收到完整的消息?

I read data from a TCP socket connection, but the server sends me \0 from time to time (which would mark the end of a message). Thus, I do not get the rest of the message.

I read like this:

uint8_t buf[tcpBufferSize];
unsigned int len = 0;

len = [inputStream read:buf maxLength:tcpBufferSize];

if(len > 0) {
    NSMutableData* data=[[NSMutableData alloc] initWithLength:0];
    [data appendBytes: (const void *)buf length:len];
    NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    //here s will be only the part before the \0

    [s release];
    [data release];
}

for example, if the server sends abc\0de y will only get abc since the \0 marks the end.

How could I receive the whole message??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

稍尽春風 2024-09-26 08:22:23

您很可能已收到整封邮件。字符串用于保存文本,而不是字节数据。如果您想保留包括空字符在内的所有数据,则需要将其保留为 NSData 对象。如果您想提取某些字节并将其解释为文本,您必须自己实现。

You most likely have received the entire message. A string is for holding text, not byte data. If you want to keep all the data including the null character, you need to leave it as an NSData object. If you want to extract certain bytes and interpret them as text, you'll have to implement that yourself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文