从 TCP 套接字接收完整消息
我从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您很可能已收到整封邮件。字符串用于保存文本,而不是字节数据。如果您想保留包括空字符在内的所有数据,则需要将其保留为 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.