简体   繁体   中英

TCP/IP Client : best way to read multiple inputstreams from server

I'm creating a java Client program that sends a command to server and server sends back an acknowledgement and a response string.

The response is sent back in this manner

client -> server : cmd_string

server -> client : ack_msg(06)

server -> client : response_msg

When I try to read the input either I'm only able to read to read just the acknowledgement message with one inputstream

My client program is able to read the message somehow(hacky method). To read the input I have to read the ack msg using Bufferedreader.

  1. This buffered reader in only able to read ack_msg not the following msg
  2. DataInputstream code is needed to read response msg.
  3. If I skip step 1 and just use Datainputstream I'm not able to read complete messages.

Client.java

try {
            Socket clientSocket = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);// ip,port

            System.out.println(" client Socket created .. ");

            PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(), true);

            String ToServer = command;
            outToServer.println(ToServer);

            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//          
            // while (!in.ready()) {
            // }
            System.out.println(in.read()); // Read one line and output it


            // ===
            byte[] messageByte = new byte[1000];//assuming msg size -need to know eact msg size ?
            boolean end = false;
            String dataString = "";
            int bytesRead = 0;

            try {
                DataInputStream in1 = new DataInputStream(clientSocket.getInputStream());
//
                while (!end) {
                    bytesRead = in1.read(messageByte);
                    dataString += new String(messageByte, 0, bytesRead);
                    if (dataString.length() > 0) {
                        end = true;
                    }
                }
                System.out.println("MESSAGE: " + dataString);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // ===

            in.close();             

            clientSocket.close();
            System.out.print("connection closed");

        } catch (Exception e) {
            System.out.print("Whoops! It didn't work!\n");
            e.printStackTrace();
        }

Output

client Socket created ..

response:6

MESSAGE: ³CO³0³Œ

connection closed

When I skip step 1

client Socket created ..

MESSAGE: -

connection closed

How can I write code that reads all the input from server(acknowledgement msg & response message & it should also check the size of data and read accordingly)?

Referred to How to read all of Inputstream in Server Socket JAVA

Thanks

These statements force the stream to be closed as soon as at least 1 byte is sent.

dataString += new String(messageByte, 0, bytesRead);
if (dataString.length() > 0) {
   end = true;
}

As soon as the ack of 6 is received the connection is closed. If the ack is ignored, the response may be sent in multiple packets, the connection would close after the first packet is received.

You must be able to determine when the ack and the response have ended.

  1. If you know how many characters are in the ack and response, you could loop like the question you referred to. You will need a loop for the ack and one for the response.
  2. If you do not know the number of characters, then you will have to look for special characters, like end-of-line or end-of-file to know when the ack line ends and when the server response ends. Look for a special character for the end of each message.
  3. A third possibility is to wait for a specific amount of time. When the time has expired, continue. This is not reliable over TCP, since data can be lost and resent. It may take more time than you allot for a response. I agree with the comment below. Originally, I hesitated to add 3 in the list. This option would most likely be used to detect a problem with the communication channel. If the time expires, then the client would give up with an error condition, it would not continue to process as if everything were alright.

You can't use both a BufferedReader and a DataInputStream over the same underlying socket. You will lose data in the BufferedReader. Use the same stream or reader for everything, and for the life of the socket. Ditto writers and output streams.

InputStream input = null;
OutputStream output = null;

Socket cs = new Socket("LocalHost", 6789);
 input = cs.getInputStream();
output = cs.getOutputStream();
 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(output));

bw.write("Send your String");
bw.flush();

int bytesRead = 0;
byte[] messageByte = new byte[1000];
String dataString = "";

bytesRead = input.read(messageByte);
dataString = new String(messageByte, 0, bytesRead);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM