Answer the question
In order to leave comments, you need to log in
Bug with BufferedReader + Socket, why are lines duplicated?
Hello, I ran into a problem when using BufferedReader in Android.
The essence of the problem: I keep a self-written Java server on a PC, ports are open and I connect from a client to Android.
The server acts as a relay of messages from one client to all and is engaged in logging.
When connecting, all clients receive a list of those who have connected and a message about the connection of a new user.
BufferedReader on PC clients works as it should, but on a mobile client, with identical code, it sometimes eats a line or displays it twice. I am attaching a screenshot on which it is marked in green as it should be, and in red, as it is bugged.
The server is written in Java 16.0.1, reading and writing to the stream goes in a separate stream (pah-pah) either in the mobile client or on the server. In the mobile client, I add the read lines to the TextView, and on the PC client I simply output it to the console, but this is so, by the way.
Please help if there is such an opportunity and if you need additional. data, I am ready to provide.
I enclose the code:
Client, method for receiving messages:
private void receiveMessage() throws IOException
{
_reader = new BufferedReader(new InputStreamReader(_clientSocket.getInputStream()));
Thread input = new Thread(() ->
{
try {
while (true)
{
_clientMessage = _reader.readLine();
runOnUiThread(() ->
{
if(_clientMessage != null)
_messages_text.append("\n\t\t" + _clientMessage);
});
}
} catch (IOException e) {
e.printStackTrace();
}
});
input.start();
}
public static synchronized void broadcastMessage(String message) throws InterruptedException
{
for (PrintWriter printWriter : _clientsList.values())
{
printWriter.println(message);
printWriter.flush();
Thread.sleep(150);
}
}
public static synchronized void showUsers() throws InterruptedException
{
broadcastMessage("CONNECTED: " + _nicknameClient);
Thread.sleep(135);
broadcastMessage("\n");
broadcastMessage("CLIENTS LIST: ");
for (String name : _clientsNicknames)
{
broadcastMessage(name.trim());
Thread.sleep(135);
}
broadcastMessage("\n");
}
Answer the question
In order to leave comments, you need to log in
Thank you all (although I'm the only one), the problem was solved.
It turned out to be the wrong synchronization of reading streams.
By adding additional sync everything is fine.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question