简体   繁体   中英

Read and write to TCP socket in Java

I am creating a simple TCP server in java which accepts clients. Each client that connects to the server sends a message, and sends an answer based on the message.

In order to accept clients I am using ServerSocket class. In order to read the client's message and write to him I am allowed to use only in the Socket , DataOutputStream and DataInputStream classes and in StandardCharsets.UTF_8 . In addition, every message that the server gets and sends must be in UTF-8 encoding.

However, I am not sure how to read and write messages in UTF-8 encoding using those classes. The size of the messages is unbounded. I tried to read about the read function of DataInputStream class, but I couldn't understand how to use it (if this indeed the function I need to use).

DataOutputStream has a writeUTF() method, and DataInputStream has a readUTF() method. Just note that these methods deal in modified UTF-8 rather than standard UTF-8, and they limit the UTF-8 data to 65535 bytes max.

It would be better to handle the UTF-8 yourself manually.

The sender can use String.getBytes() to encode a String to a byte[] array using StandardCharsets.UTF_8 , then send the array's length using DataOutputStream.writeInt() , and then finally send the actual bytes using DataOutputStream.write(byte[]) .

The receiver can then read the array length using DataInputStream.readInt() , then allocate a byte[] array and read it using DataInputStream.readFully() , and then finally use the String constructor to decode the bytes using StandardCharsets.UTF_8 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM