-1

I have designed a Java Client class that is required to send a byte[] array to a Java Server class via a socket. Here is my code:

ByteArrayClient.java

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ByteArrayClient {

public static void main(String[] args) {


        //make POJO__________________________
        ByteEncodeSubscriptionReq sr1=ByteEncodeSubscriptionReq.makeRequest(103, "Str1", "Str2");

        //Connection details____________________
        String serverName = "localhost";
        int port = 6060;
        try {

            //Establish Connection with server_______________________________
            System.out.println("ByteArrayClient: Connecting to " + serverName +":" + port+"...");
            Socket client = new Socket(serverName, port);//make new socket
            System.out.println("ByteArrayClient: connected to " + client.getRemoteSocketAddress());

            //Encode POJO to ByteArray________________________________
            byte[] SubscripReqByteArray=ByteEncodeSubscriptionReq.encode(sr1);
             //encoded correctly to a 44 bit byte array
            System.out.println("ByteArrayClient: SubscripTionRequest successfully encoded");

            //Send POJO ByteArray to server__________________________
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(out);
            os.write(SubscripReqByteArray);;

            System.out.println("ByteArrayClient: POJO sent to server");

            //Receive Server response_________________________________
            InputStream inFromServer = client.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);
            System.out.println("ByteArrayClient received: " + in.readUTF());

            //close socket____________________________________
            client.close();


        } catch (IOException e) {

            e.printStackTrace();
            System.out.println("PojoClient: Connection Failed");
        }

    }

}

...and ByteArrayServer.java

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException; 


public class ByteArrayServer extends Thread{

        private ServerSocket serverSocket;

        public ByteArrayServer(int port) throws IOException {
            serverSocket = new ServerSocket(port);//create server socket 
            serverSocket.setSoTimeout(15000);//socket closes after 15 seconds
            this.start();
        }

        public void run() {
            while (true) {//server runs infinitely______________
                try {

                    System.out.println("ByteArrayServer: Waiting for client on port " + serverSocket.getLocalPort() + "...");
                    Socket servedClient = serverSocket.accept();//client socket

                    System.out.println("ByteArrayServer: connected to " + servedClient.getRemoteSocketAddress());

                    //Receive Client ByteArray___________________________________________
                    ByteEncodeSubscriptionReq receivedReq=new ByteEncodeSubscriptionReq();//server side POJO
                    System.out.println("ByteArrayServer: created SubscriptionReq Object");
                    InputStream PojoStreamHolder = servedClient.getInputStream();
                    System.out.println("ByteArrayServer: client InputStream received");
                    byte[] clientByteStream=new byte[44];//same size as Pojo byte requirement


                    _____/*MY CODE IS STUCK SOMEWHERE HERE*/__________      



                    servedClient.getInputStream().read(clientByteStream);

                    System.out.println("ByteArrayServer: clientByteStream received: "+clientByteStream[0]+" "+clientByteStream[1]);
                    receivedReq=ByteEncodeSubscriptionReq.decode(clientByteStream);

                    //Send confirmation to Client__________________________________________________
                    DataOutputStream out = new DataOutputStream(servedClient.getOutputStream());
                    if(receivedReq.getRequestSymbol().trim().length()!=0){
                            out.writeUTF("ByteArrayServer received Subscription ID="+receivedReq.getSubscriptionID());
                            System.out.println("ByteArrayServer: new SubscriptionRequest ID="+receivedReq.getSubscriptionID()+" Subscriber_Name="+receivedReq.getSubscriberName());
                    }else{
                            out.writeUTF("ByteArrayServer: did not receive Subscription ID");
                    }
                    //Close Client socket_________________________________________________________
                    //server.close();

                    //serverSocket.close();



                } catch (SocketTimeoutException s) {
                    System.out.println("PojoServer: Socket timed out after " + getTimeElapsedInSeconds(startTime) + " seconds from start");
                    break;
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }



        public static void main(String[] args) {
            // int port = Integer.parseInt(args[0]);//to get port as an Argument
            int port = 6060;
            try {
                Thread t = new ByteArrayServer(port);
                startTime = System.currentTimeMillis();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

Here is the Server console output:

ByteArrayServer: Waiting for client on port 6060...
ByteArrayServer: connected to /127.0.0.1:64233
ByteArrayServer: created SubscriptionReq Object
ByteArrayServer: client InputStream received

The issue is that while the Stream is received by the server without errors, it gets stuck near servedClient.getInputStream().read(clientByteStream); method and does not proceed further.

I've also tried

int count=servedClient.getInputStream().read(clientByteStream);

and

DataInputStream in = new DataInputStream(servedClient.getInputStream());
long bStr=in.readLong();

and

ObjectInputStream PojoObjHolder = new ObjectInputStream(PojoStreamHolder);
byte[] clientByteStream2 = (byte[])PojoObjHolder.readObject();

..but they show the same problem as well.

How should I pass the Byte Array between the two classes without extra imports?

Saransh Kejriwal
  • 2,467
  • 5
  • 15
  • 39
  • Your code makes no sense whatsoever. You are sending to the server with an `ObjectOutputStream` and reading at the server with a `DataInputStream`. – user207421 Sep 28 '16 at 08:40
  • Thanks for the input. I've made that change – Saransh Kejriwal Sep 28 '16 at 08:41
  • 1
    In fact you haven't written anything to the server whatsover. Only to the `ByteArrayOutputStream`. I don't know what change you're referring to. I didn't suggest one. – user207421 Sep 28 '16 at 08:43

2 Answers2

0

DataInputStream.readFully(byte[] b) will finish only when in inputstream bytes till b.length available. So for sure you need to debug if you have all the bytes or not.And the solution is to make those byte available so that the function will finish. Same for DataInputStream.read(byte[] b) The method is blocked until input data is available. Please make sure by debugging your app that inputstream have 44 bytes. Try below to count available bytes and you can read those easily.

// count the available bytes form the input stream int count = is.available();

     // create buffer
     byte[] bs = new byte[count];

     // read data into buffer
     dis.read(bs);
user207421
  • 305,947
  • 44
  • 307
  • 483
  • Youre statement about `DataInputStream.read(byte[] b)` appears to imply that it behaves the same as `DataInputStream.readFully(byte[] b)`, which it doesn't. Please clarify. – user207421 Sep 28 '16 at 08:42
  • Thanks EJP but the main difference is readfully read exact bytes as length of b and read can read may be less than length of b – Ekant Sharma Sep 28 '16 at 09:47
0

The problem was in my ByteArrayClient Class. I had to link the OutputStream with the client socket, rather than creating a new instance of it. So I replaced:

ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.write(SubscripReqByteArray);;

with

OutputStream os = client.getOutputStream(out);
os.write(SubscripReqByteArray);;

Thank you for the hint Ekant

Saransh Kejriwal
  • 2,467
  • 5
  • 15
  • 39