Issue with sending multiple commands over a socket connection

443 views Asked by At

I'm trying to send a command and have it execute through a socket connection. I need to read each response line, then continue sending commands to the same process. Below I have the methods that handle that.

Currently, I receive a response when I initially open the socket connection, but after, the program hangs until the foreign host closes the connection, presumably because no input was entered in a specified amount of time.

public static void main(String[] args) {

        try {
            sendSmtpTest("anEmail@aRandomDomain");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
   public static boolean sendSmtpTest(String address) throws Exception {

        Socket socket = new Socket("a.random.address", 0000);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedWriter out =  new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

        int res;
        System.out.println("1");
        System.out.println(in.readLine());

        System.out.println("2");
        System.out.println(in.readLine());
        say(out, "HELO netatlantic.com");

        System.out.println("3");
        System.out.println(in.readLine());

        System.out.println("4");
        System.out.println(in.readLine());
        say(out, "MAIL FROM: <[email protected]>");

        System.out.println("5");
        System.out.println(in.readLine());
        say(out, "RCTP TO: <" + address + ">");

        System.out.println("6");
        System.out.println(in.readLine());
        say(out, "RSET");

        System.out.println("7");
        say(out, "QUIT");

        // clean up
        in.close();
        in.close();
        out.close();

        return true;

    }
   private static void say(BufferedWriter wr, String text) throws IOException {
        wr.write((text + "\r\n"));
        wr.newLine();
        wr.flush();

    }

The random printing of the numbers are a way for me to know where in the program it is at. Also, I have to run this off of a server, thus I cannot run it in a debugger because the socket I'm connecting to only accepts connections from a specific address. Thanks!

1

There are 1 answers

1
erickson On BEST ANSWER

You mean that you see the 220 status from the SMTP server print out, but then it just hangs?

That's because you are waiting for another line to be sent from the server, but it's waiting for your HELO command. (Right after your "2" statement.) Remove that extra System.out.println(in.readLine()); and see if you make progress.

If not, post the output from your program so that your question is more understandable.