0

I am trying to send a string terminated with \0 to a tcp socket but it seems the \0 does never reach its destination.

Using this code:

NSString* s=@"<b/> \0_";

uint8_t *buf = (uint8_t *)[s UTF8String];

int resCode = [outputStream write:buf maxLength:strlen((char *)buf)];

I only seem to send @"<b/> ". Probably the \0 is seen as the end of the uint8_t.

Can someone tell me how it should be done??

Daniel
  • 20,420
  • 10
  • 92
  • 149
  • 3
    Don't use an NSString to send data. Use NSData or a buffer of bytes. – bbum Aug 11 '10 at 15:47
  • You should really check out some information how strings work. Especially how strings are escaped, then you will know why strlen doesn't return the valid length. – miho Sep 10 '12 at 11:49

2 Answers2

4

Of course it sends it without \0. strlen will return you length of the string, not counting null-terminators. Change it to something like

[outputStream write:buf maxLength:(strlen((char *)buf) + 1)]

sha
  • 17,824
  • 5
  • 63
  • 98
  • You could add that the problem has got nothing to do with the `NSString` class, but only with the understanding of C`s string functions. Also, it's not necessary to terminate the NSString with the NUL character, that's done by `UTF8String`. – Nikolai Ruhe Aug 11 '10 at 14:47
  • The \0 character is not used to terminate a NSString, but to terminate a commando at the server. @sha: Thanks a lot, it worked like a charm =) – Daniel Aug 11 '10 at 14:55
  • @dkk I understand, but since `UTF8String` returns a null terminated C string, you don't have to add that character in the `NSString`. – Nikolai Ruhe Aug 11 '10 at 17:55
-2

Why do you want to send ']0] character in your String.....

Can't you use any other character...because '\0' character is always treated as terminating character!

And if you really want to send it that way then send a different character and map it to '\0' when you receiv it!

SPatil
  • 1,003
  • 8
  • 13