3 Replies Latest reply: Apr 22, 2012 10:13 AM by baftos RSS

    Socket communication - inputstream / byte[]

    896810
      Hello, I need help please. I have ServerSocket and Socket ... I can send data type STRING, but i need send byte array or InputStream, that's I do not care, ale I need to send it. I have been try it 2 days and I'm desperate. Can you see to me some basic example how send between sockets byte[] or InputStream?? Thank you very much.
        • 1. Re: Socket communication - inputstream / byte[]
          EJP
          socket.getOutputStream().write(byteArray);
          It's somewhat surprising that you laboured for two whole days without discovering that.
          • 2. Re: Socket communication - inputstream / byte[]
            896810
            Thank you. I have this. Now I would to ask, if it's good way or bad, because receiving side byte array correct receive and success save, because byte[] I am using for file. Problem I have with server, because throw exception --> image. How to repair it. I tried delete row with dos.flush(), but exception is the same. But row 84.

            Error

            // Sending side
                      byte[] data = getByteArrayFromInputStream(inputStream);
                      
                      DataOutputStream dos = null;
                      try {
                           dos = new DataOutputStream(socket.getOutputStream());
                           dos.writeInt(data.length);
                           dos.write(data);
                           dos.flush();
                      } catch (IOException e) {
                           // TODO Auto-generated catch block
                           e.printStackTrace();
                      }

            // Receiving side
                 private void receiveFile() throws IOException {
                      DataInputStream dis = null;

                      dis = new DataInputStream(clientSocket.getInputStream());
                      int length = dis.readInt();
                      
                      byte[] b = new byte[length];
                      dis.read(b);
                      dis.close();
            }

            Edited by: 893807 on 22.4.2012 8:06

            Edited by: 893807 on 22.4.2012 8:11

            Edited by: 893807 on 22.4.2012 8:12
            • 3. Re: Socket communication - inputstream / byte[]
              baftos
              Read very carefully the API documentation for DataInputStream.read(byte[]). Compare it with DataInputStream.readFullly(byte[]).