The code socket.getOutputStream().write(String.valueOf("5000").getBytes());
sends 4 bytes, because Java use 16 bits chars ONLY for non ASCII character as specified in Java Language Specification 3.10.5.
To be sure, you have to print the value of nread
in C program.
The code nread = recv(clientSocket,Buffer,1024,0);
receives 4 characters and DOESN'T put the zero to terminate the string, so printf display the contents of the (non initailized) buffer, I suggest memset( Buffer, 0, sizeof( Buffer ))
Code suggested:
if( nread < 0 ) {
perror("Read error");
return;
}
Buffer[nread] = '\0';
To encode and decode messages and streams I usually use java.nio.ByteBuffer
To encode and send ASCII 7 java.lang.String:
import java.nio.ByteBuffer;
public final class SerializerHelper {
public static void putString( String s, ByteBuffer target ) {
final byte[] bytes = s.getBytes();
target.putInt( bytes.length );
target.put( bytes );
}
public static void putBoolean( boolean value, ByteBuffer target ) {
target.put((byte)( value ? 1 : 0 ));
}
public static boolean getBoolean( ByteBuffer source ) {
return source.get() != 0;
}
public static String getString( ByteBuffer source ) {
final int len = source.getInt();
final byte[] bytes = new byte[len];
source.get( bytes );
return new String( bytes );
}
}
In C:
uint32_t len = strlen( s );
uint32_t lenForNet = htonl( len );
char * p = buffer;
memmove( p, &lenForNet, sizeof( lenForNet ));
p += sizeof( lenForNet );
memmove( p, s, len );
send( sckt, buffer, len + sizeof( LenForNet ), 0 );