Skip to content
Advertisement

how to implement ByteArrayOutputStream?

I need help with implementing an byteArrayOutputStream that stores the output from the server, which I can then read from and print. Does anyone know how to do this? Any help would be much appreciated.

TCPAsk:

import java.net.*;
import java.io.*;
import tcpclient.TCPClient;

public class TCPAsk {
    /*
     * Usage: explain how to use the program, then exit with failure status
     */
    private static void usage() {
        System.err.println("Usage: TCPAsk host port <data to server>");
        System.exit(1);
    }

    /*
     * Main program. Parse arguments on command line and call TCPClient
     */
    public static void main( String[] args) {
        String hostname = null;
        int port = 0;
        byte[] userInputBytes = new byte[0];

        try {
            // Get mandatory command line arguments: hostname and port number
            int argindex = 0;
            hostname = args[argindex++];
            port = Integer.parseInt(args[argindex++]);

            // Remaining arguments, if any, are string to send to server
            if (argindex < args.length) {
                // Collect remaining arguments into a string with single space as separator
                StringBuilder builder = new StringBuilder();
                boolean first = true;
                while (argindex < args.length) {
                    if (first)
                        first = false;
                    else
                        builder.append(" ");
                    builder.append(args[argindex++]);
                }
                builder.append("n");
                userInputBytes = builder.toString().getBytes();
            }
        } catch (ArrayIndexOutOfBoundsException | NumberFormatException ex) {
            // Exceeded array while parsing command line, or could
            // not convert port number argument to integer -- tell user
            // how to use the program
            usage();
        }

        try {
            TCPClient tcpClient = new tcpclient.TCPClient();
            byte[] serverBytes  = tcpClient.askServer(hostname, port, userInputBytes);
            String serverOutput = new String(serverBytes);
            System.out.printf("%s:%d says:n%s", hostname, port, serverOutput);
        } catch(IOException ex) {
            System.err.println(ex);
            System.exit(1);
        }
    }
}

Edit: my code is now working and it is similar to the answer (TCPClient) given below with some minor additions. ByteArrayOutputStream is not needed.

Advertisement

Answer

You didn’t send the user data to the server. Just modify TCPClient like this:

package tcpclient;

import java.net.*;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class TCPClient
{
    public TCPClient()
    {}

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

        byte[] bufferSize = new byte[1000];

        //send message to the server
        clientSocket.getOutputStream().write(toServerBytes);

        // Query response
        String response;
        // Length of response
        int responseLength;
        StringBuilder sb = new StringBuilder();

        while((responseLength = clientSocket.getInputStream().read(bufferSize)) != -1)
        {
            response = new String(bufferSize, 0, responseLength, StandardCharsets.UTF_8);
            sb.append(response);
        }

        clientSocket.close();
        return sb.toString().getBytes();
    }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement