1

I've got a client/server protocol running through TCP/IP. Without the code:

String fileName = "output.txt";
final boolean append = true, autoflush = true;
PrintStream printStream = new PrintStream(new FileOutputStream(fileName,append));
...
...
System.setOut(printStream);

I can get the output I want in the server terminal. However, when I add the code (from above) only the part of the terminal displays the output, and the rest gets saved in the text file. I'm glad it saves in the text file, but I want it to output to the terminal as well for demonstration purposes.

What can I do to alter the code to achieve getting it to output onto the terminal, but also save the terminal in the output.txt file?

Below are the server and client code if you'd like to test it.

Server.java

package TCPSocket;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class TCPServer{
    private ServerSocket server;

    /**
     * The TCPServer constructor initiate the socket
     * @param ipAddress
     * @param port
     * @throws Exception
     */
    public TCPServer(String ipAddress, int port) throws Exception {
        if (ipAddress != null && !ipAddress.isEmpty())
            this.server = new ServerSocket(port, 1, InetAddress.getByName(ipAddress));
        else
            this.server = new ServerSocket(0, 1, InetAddress.getLocalHost());
    }

    /**
     * The listen method listen to incoming client's datagrams and requests
     * @throws Exception
     */


    private void listen() throws Exception {
        // listen to incoming client's requests via the ServerSocket
        //add your code here
        String data = null;
        Socket client = this.server.accept();
        String clientAddress = client.getInetAddress().getHostAddress();
        System.out.println("\r\nNew client connection from " + clientAddress);

        String serverIP = "192.168.56.1"; // local IP address
        int port = 7077;

        String fileName = "output.txt";
        final boolean append = true, autoflush = true;
        PrintStream printStream = new PrintStream(new FileOutputStream(fileName,append));


        // print received datagrams from client
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

        while ( (data = in.readLine()) != null && !data.equals("QUIT")) {


            try {
                if (data.startsWith("HELLO")) {
                    System.out.println("\r\nC: " + data);
                    System.out.println("\r\nS: 250 " + data.toLowerCase() + ", pleased to meet you");
                } else if (data.startsWith("MAIL FROM: ")) {
                    System.out.println("\r\nC: " + data);
                    System.out.println("\r\nS: 250 ok");
                } else if (data.startsWith("RCPT TO: ")) {
                    System.out.println("\r\nC: " + data);
                    System.out.println("\r\nS: 250 ok");
                } else if (data.equals("DATA")) {
                    System.out.println("\r\nC: " + data);
                    System.out.println("\r\nS: 354 End data with <CR><LF>.<CR><LF>");
                } else if (data.equals(".")) {
                    System.out.println("\r\nC: " + data);
                    System.out.println("\r\nS: 250 ok Message accepted for delivery");
                } else
                    System.out.println("\r\nC: " + data);

                client.sendUrgentData(1);
                System.setOut(printStream);


            } catch (IOException e) {
                System.out.println(e);
            }

        }

                System.out.println("\r\nC: " + data);
                System.out.println("\r\nS: 221 " + serverIP + " closing connection");
    }





    public InetAddress getSocketAddress() {
        return this.server.getInetAddress();
    }

    public int getPort() {
        return this.server.getLocalPort();
    }


    public static void main(String[] args) throws Exception {
        // set the server address (IP) and port number
        //add your code here
        String serverIP = "192.168.56.1"; // local IP address
        int port = 7077;

        if (args.length > 0) {
            serverIP = args[0];
            port = Integer.parseInt(args[1]);
        }
        // call the constructor and pass the IP and port
        //add your code here
        TCPServer server = new TCPServer(serverIP, port);
        System.out.println("\r\nRunning Server: " +
                "Host=" + server.getSocketAddress().getHostAddress() +
                " Port=" + server.getPort());
        System.out.println("220 gov.uk");
        server.listen();
    }

}

Client.java

package TCPSocket;
import java.io.*;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class TCPClient{
    private Socket tcpSocket;
    private InetAddress serverAddress;
    private int serverPort;
    private Scanner scanner;


    /**
     * @param serverAddress
     * @param serverPort
     * @throws Exception
     */
    private TCPClient(InetAddress serverAddress, int serverPort) throws Exception {
        this.serverAddress = serverAddress;
        this.serverPort = serverPort;

        //Initiate the connection with the server using Socket.
        //For this, creates a stream socket and connects it to the specified port number at the specified IP address.
        //add your code here
        this.tcpSocket = new Socket(this.serverAddress, this.serverPort);
        this.scanner = new Scanner(System.in);
    }

    /**
     * The start method connect to the server and datagrams
     * @throws IOException
     */
    private void start() throws IOException {
        String input;
        //create a new PrintWriter from an existing OutputStream (i.e., tcpSocket).
        //This convenience constructor creates the necessary intermediateOutputStreamWriter, which will convert characters into bytes using the default character encoding
        while (true) {
            input = scanner.nextLine();
            PrintWriter output = new PrintWriter(this.tcpSocket.getOutputStream(), true);
            output.println(input);
            output.flush();

            try{
                if(input.equals("QUIT")){
                    tcpSocket.close();
                    break;
                }
            }catch (IOException e) {
                System.out.println(e);
            }
        }
    }


    public static void main(String[] args) throws Exception {
        // set the server address (IP) and port number
        //add your code here
        InetAddress serverIP = InetAddress.getByName("192.168.56.1"); // local IP address
        int port = 7077;

        if (args.length > 0) {
            serverIP = InetAddress.getByName(args[0]);
            port = Integer.parseInt(args[1]);
        }

        // call the constructor and pass the IP and port
        //add your code here
        TCPClient client = new TCPClient(serverIP, port);
        System.out.println("\r\n Connected to Server: " + client.tcpSocket.getInetAddress());
        client.start();
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • This line `System.setOut(printStream);` makes all the terminal code instead go to the printStream. Remove that line and it will remain in the terminal. If you want the information to show up on both then you need to use both `System.out.println(yourMessage);` and `printStream.print(yourMessage);`, or you need to split the stream, or make a custom class to do both actions for you. – sorifiend Mar 10 '21 at 21:34

1 Answers1

0

The way I managed to fix it so it shows both in the terminal and Output.txt is by using the printStream method suggested by @sorifiend.

By moving printStream.println("\r\nC: " + data); before the if-statement saves the client message first in the text file

private void receiveMessage() throws Exception {
    // listen to incoming client's requests via the ServerSocket
    //add your code here
    String data = null;
    Socket client = this.server.accept();
    String clientAddress = client.getInetAddress().getHostAddress();
    System.out.println("\r\nNew client connection from " + clientAddress);

    String serverIP = "192.168.56.1"; // local IP address
    int port = 8088;

    PrintStream originalSysOut=System.out;

    String fileName = "output.txt";
    final boolean append = true, autoflush = true;
    PrintStream printStream = new PrintStream(new FileOutputStream(fileName,append));

    // print received datagrams from client
    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    while ( (data = in.readLine()) != null && !data.equals("QUIT")) {

        try {
            printStream.println("\r\nC: " + data);
            if (data.startsWith("HELLO")) {
                System.out.println("\r\nC: " + data);
                System.out.println("\r\nS: 250 " + data.toLowerCase() + ", pleased to meet you");
                printStream.println("\r\nS: 250 " + data.toLowerCase() + ", pleased to meet you");
            } else if (data.startsWith("MAIL FROM: ")) {
                System.out.println("\r\nC: " + data);
                System.out.println("\r\nS: 250 ok");
                printStream.println("\r\nS: 250 ok");
            } else if (data.startsWith("RCPT TO: ")) {
                System.out.println("\r\nC: " + data);
                System.out.println("\r\nS: 250 ok");
                printStream.println("\r\nS: 250 ok");
            } else if (data.equals("DATA")) {
                System.out.println("\r\nC: " + data);
                System.out.println("\r\nS: 354 End data with <CR><LF>.<CR><LF>");
                printStream.println("\r\nS: 354 End data with <CR><LF>.<CR><LF>");
            } else if (data.equals(".")) {
                System.out.println("\r\nC: " + data);
                System.out.println("\r\nS: 250 ok Message accepted for delivery");
                printStream.println("\r\nS: 250 ok Message accepted for delivery");
            } else
                System.out.println("\r\nC: " + data);

            client.sendUrgentData(1);

        } catch (IOException e) {
            System.out.println(e);
        }
    }
    System.setOut(printStream);
    System.out.println("\r\nC: " + data);
    System.out.println("\r\nS: 221 " + serverIP + " closing connection");

}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197