0

I'm trying to create a very simple client-server program. My aim is to send a message to the server after connecting succesfully but I need to be able to store the message using byteArrayOutputStream and also byteArrayInputStream later just in case something goes wrong along the way. This is my code so far:

public class TCPClient
{

    public byte[] askServer(String hostname, int port, byte[] toServerBytes) throws IOException
    {
            Socket clientSocket = new Socket(hostname, port);
            
            String Message;
            StringBuilder sb = new StringBuilder();

            try {

                clientSocket.getOutputStream().write(toServerBytes(StandardCharsets.UTF_8));
                ByteArrayOutputStream fromClient = new ByteArrayOutputStream();
                byte[] b = fromClient.toByteArray();

            }
Dyson
  • 23
  • 6
  • 1
    You already found `ByteArrayOutputStream`, what more do you need? You can write bytes to it one by one or multiple in one go (from an array). It will take care of the resizing of its internal storage, and the `toByteArray()` you also already found will return (a copy of) the currently written bytes. – Rob Spoor Feb 14 '22 at 15:52
  • Ok, thanks. I thought I had written something incorrectly since my code refuses to run but it must be something else then. It's a several page long code so I thought maybe it would be too much to post on here so only posted the part I thought I had written incorrectly. – Dyson Feb 14 '22 at 15:58
  • Your `byte[] b` is empty right now. You created a new empty `ByteArrayOutputStream`. You probably want to save the results of `toServerBytes` inside `b` – user1738539 Feb 14 '22 at 16:01
  • You write `toServerBytes` to the client's output stream. You now need to read from the client's input stream and write it to the `ByteArrayOutputStream`. That can probably be as easy as `clientSocket.getInputStream().transferTo(fromClient)`. – Rob Spoor Feb 14 '22 at 16:10
  • You can use `List byteArray = new ArrayList<>();` instead of `byte[]`, though the stream option seems better suited. – Igor Flakiewicz Feb 14 '22 at 17:27

0 Answers0