Java Socket Error: reading strings from Socket InputStream

I am using Socket to communicate with ServerSocket. Lines are sent from the server to my Socket. Each individual line is a message that contains information in the analysis. To read these lines of text, a scanner is used.

The problem is that the data comes in "bursts". Despite the fact that the Server constantly and evenly transmits data, the data read by the scanner on the client side seems to be a pause, at the same time a bunch of messages are read (30-40), and then paused again. He repeats this cycle endlessly.

If I increase the data transfer rate, the duration of the pauses is reduced; if I slow down the data (up to 1 message per second), the error persists and the pauses become very long. It is almost as if Socket was waiting for a buffer overflow before sending any data to the Scanner; then resets everything and waits for overflow again. However, if I reduce the size of the Socket buffer, nothing will change at all.

It should be noted that I used Scanner and Socket in this method before - on the server side - and everything worked as desired. In addition, I a) tried this using BufferedReader, for example, with Java tutorials (no changes in the error) and b) printed the Server transfer list to a file and read from the file in the same way, and the program worked as expected (constant speed receiving messages, etc.), so the problem seems to be in Socket itself.

So: How can I fix this behavior? I have no ideas, and I really don't know what is going on.

CODE (on request):

// In try block // Makes the connection Socket connection = new Socket(TARGET_MACHINE, PORT_NUMBER); Scanner reader = new Scanner(connection.getInputStream()); 

 // In new Thread // In run() while(!finished) // Boolean exit strategy { if(reader.hasNextLine()) Sring message = reader.nextLine(); } 

The way I concatenate and extract strings.

Also, the lines that I get usually have a length of about 20-40 characters.

+6
source share
2 answers

Do you flush the stream every time you write it from the server side? This may be buffering the output and not writing it to the stream until it reaches a certain threshold.

+2
source

Perhaps you are using readLine to read data?

Here is an excerpt from javadoc that may be of interest to you:

Since this method continues searching through an input looking for a line separator, it can buffer the entire input search to scroll through the line if there are no line separators.

Can you attach client and server code to find out what is wrong? It would be nice if you use a very simple byte byte reader to check the stream from the server with pauses in transport, maybe the problem is how you write data to the server socket ... it's hard to guess without code :)

+2
source

Source: https://habr.com/ru/post/890244/


All Articles