简体   繁体   中英

Java Socket program can not read data if the server sends data using write and recieves data using readUTF()

I have written a socket program where the client uses readUTF() and writeUTF() to communicate with the server while the server uses read() and write() to communicate with client.

My server can read all the data coming from server. I am using write() on the server side and readUTF() in client side.

So, in this scenario my client is unable to get all the data that is sent by the server if the data size is large, only some portion of data is received.

What should be done to ensure that all data is transmitted?

Do not use readUTF and writeUTF in this scenario. Instead read and write byte arrays:

read(byte [] b)

Then convert the byte array to a String using the appropriate String constructor:

public String(byte[] bytes,
              String charsetName)

You should try-catch UnsupportedEncodingException exceptions.

Note that readUTF and writeUTF use a modified form of UTF. I don't know what you're sending using read() and write() on the server, but you should ensure that there's compatibility between what the client expects and what the server expects.

I would make both client and server send/receive using the same method. I don't know if that's causing your problem, but it will save you some unrelated grief.

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