Socket c bytes received but I can't print the String -
i use code receive string java server in c client.
if( recv( to_server_socket, &reply, sizeof( reply ), msg_waitall ) != sizeof( reply ) ) { printf( "socket read failed"); exit( -1 ); } printf( "got reply: %d\n", ntohl( reply ) ); char buf[512]; ssize_t nbytes=0; int byte_count; byte_count = recv(to_server_socket, buf, sizeof buf, 0); printf("recv()'d %d bytes of data in buf\n", byte_count); buf[byte_count] = '\0'; printf("string : %s\n",buf);
for example, when java server sends string
bzzrecyvemjmif
i got result
recv()'d 16 bytes of data in buf string :
so received 16 bytes
printf("string : %s",buf);
don't show me anything.
the server sent string
tyvudbbkalp3scp
i tried code
int i=0; while(i<byte_count){ printf("string : %c\n",buf[i]); i++; recv()'d 17 bytes of data in buf
and result have
string : string : string : string : t string : y string : v string : u string : d string : b string : b string : k string : string : l string : p string : 3 string : s string : c string : p
it appears java sending length-prefixed string. first 2 bytes correspond length field. these 2 bytes determine how many bytes follow. here's how i'd serialise , print that:
unsigned int str_len = buf[0] * 256 + buf[1]; char *str = buf + 2; /* printf("%.*s\n", str_len, str); // use this, instead of following 2 lines: */ fwrite(str, 1, str_len, stdout); putchar('\n');
a byte value 0
denotes end of string, in c. explains why string pointed buf
appears empty. explains why embedded characters in length-prefixed string have value 0
cause commented out printf
in code cease printing string.
it's character value doesn't have well-defined visual representation. explains why embedded characters in length-prefixed string cause fwrite
print awkward-looking characters.
Comments
Post a Comment