【问题标题】:Issue with sending multiple commands over a socket connection通过套接字连接发送多个命令的问题
【发布时间】:2015-06-24 19:36:23
【问题描述】:

我正在尝试发送命令并让它通过套接字连接执行。我需要阅读每个响应行,然后继续向同一进程发送命令。下面我有处理它的方法。

目前,我最初打开套接字连接时收到响应,但之后,程序挂起,直到外部主机关闭连接,大概是因为在指定的时间内没有输入任何输入。

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: <abuse@netatlantic.com>");

        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();

    }

数字的随机打印是一种让我知道它在程序中的位置的方法。另外,我必须在服务器上运行它,因此我不能在调试器中运行它,因为我要连接的套接字只接受来自特定地址的连接。 谢谢!

【问题讨论】:

  • 您可以运行远程调试器。

标签: java sockets bufferedreader bufferedwriter


【解决方案1】:

您的意思是您看到 SMTP 服务器打印出来的 220 状态,但它只是挂起?

那是因为您正在等待服务器发送另一条线路,但它正在等待您的 HELO 命令。 (就在您的“2”语句之后。)删除多余的System.out.println(in.readLine());,看看您是否取得了进展。

如果没有,请发布您的程序的输出,以便您的问题更容易理解。

【讨论】:

  • 太棒了,成功了!在发布之前,我尝试了几个小时,并尝试了不同的方法。我会尽快接受你的回答。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-06-05
  • 2019-06-12
  • 1970-01-01
  • 2012-08-09
  • 2014-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多