Search code examples
javasocketsutf-8tcpbyte

If I need to send only 1 byte via a socket, can I just use one char?


I have a client - server program using TCP. Now I want to send different messages of different size. I read that a char in Java is 2 bytes. If I am using UTF-8, can I just send a char and it will be of size 1 byte?

Also which is better to use: DataInputStream and DataOutputStream or BufferedInputStream and BufferedOutputStream ?


Solution

  • The usual convention in Java is to write bytes using OutputStream. Neither of the methods here accepts char. You would need to convert the character to byte[] array e.g.

    OutputStream out = ...
    byte[] bytes = "my string".getBytes(Charset.forName("UTF-8"));
    out.write(bytes);
    

    If you plan to use sockets you can check Socket.getOutputStream() method:

    Returns an output stream for this socket.

    If this socket has an associated channel then the resulting output stream delegates all of its operations to the channel. If the channel is in non-blocking mode then the output stream's write operations will throw an IllegalBlockingModeException.

    Closing the returned OutputStream will close the associated socket.