Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Getting multiple lines from socket

Tags:

java

sockets

line

I have a Java application that consists of a client and a server. The client sends encrypted commands to the server, and the server executes them.

The problem that I am having right now is that, with my encryption algorithm, sometimes the encrypted command contains "\n" or "\r" characters, which mess up my server code. This is because I am using the readLine() method, which stops when it finds a line terminator. What I need is a way to read all the characters the client sends into one string.

Here is my code:

public void run(){            
        System.out.println("Accepted Client!");

        try{                                
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "ISO8859_1"));
            out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "ISO8859_1"));

            String clientCommand = null;

            while(RunThread){                    
                // read incoming stream
                do{
                    clientCommand = in.readLine();
                }while(clientCommand == null);

                //decrypt the data
                System.out.println("Client: " + clientCommand);

                if(clientCommand.equalsIgnoreCase("quit")){
                    RunThread = false;
                }else{
                    //do something
                    out.flush();
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
  }

Everything I've tried (various forms of nested loops using the read() function) hasn't worked. I would welcome any help or suggestions. Thanks, everyone!

like image 626
Jason Avatar asked May 20 '26 05:05

Jason


1 Answers

I don't see encryption in the code you posted, but usually it's not a good idea to rely on separator characters.

When sending binary data, you should prepend the length of the data to the stream, and then you know exactly how many bytes to expect (and when the message will end.) It's more efficient to do things that way too instead of looking for a newline character.

like image 103
takteek Avatar answered May 21 '26 19:05

takteek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!