Skip to content
Advertisement

Send Data between client and server as a byte array

I am trying to send encrypted data between a client and server. Due to the RSA encryption its in Byte array form. This means I have had to change the way I send data. I curently cant get it working, Ill leave my method (sendMessage) below which is what handles the sending of the message, If anyone could tell me what I am doing wrong that would be great 🙂

 public void sendMessage(byte[] msg){ 
        if(msg.equals("null")){
                
                
        }        
        else{
            try{
            ByteArrayOutputStream f = new ByteArrayOutputStream(CSocket.getOutputStream());
            out = new PrintWriter(f);
            out.write(msg);
            countSend++;
            }catch (IOException e){
                System.out.println("ERROR");
            }
        }       
 
    }  



Sorry should have clarified, essentially CSocket is a socket I have opend and I want to send msg through the socket. The issue I have specifically with this code is It says that: OutputStream can not be converted to int on the line where I creat the ByteArrayOutputStream object f and No suitable method found for write(byte[]) on the line out.write(msg);

Advertisement

Answer

I think I fixed my issue now. Its probibably not the most efficient way of doing it but essentially I encode the byte array in a format that means I wont loose any data. This means I send it in this encoded format and then on the receving end I just simply decode it. Works so much better with print writer doing it this way.

OutputStream f = CSocket.getOutputStream();
out = new PrintWriter(f);
String encodedmsg = new String(msg, "ISO-8859-1"); // ISO-8859-1 is supposed to give every character a unique representation so I shouldent loose any data during encoding and decoding
out.write(encodedmsg);

Advertisement