【问题标题】:SocketTimeoutException in client readLine() method on AWSAWS 上客户端 readLine() 方法中的 SocketTimeoutException
【发布时间】:2016-01-25 00:58:36
【问题描述】:

更新:

我注意到它在 Windows 机器上运行良好,但在 Mac 上却失败了。

我为套接字连接创建了一个基本的 Java 服务器代码。它在 AWS Linux AMI 上运行,我从我的计算机建立了客户端连接。它适用于客户的前 4-5 个答案。但是,在第 4 个或第 5 个答案之后,我没有得到服务器的任何响应,它只是挂起。过了一会儿,它给出了SocketTimeout Exception。

我在两边都用 setSoTimeout() 设置了套接字超时,它没有改变任何东西。我想知道这是否与亚马逊有关。

客户代码:

public static void main(String[] args) {
    final int portNumber = 9090;
    String connected = "1";
    System.out.println(WELCOME);

    try {
        Socket socket = new Socket("ip", portNumber);
        socket.setSoTimeout(0);
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader input = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
        out.println(connected);
        while (connected.equals("1")) {
            //read in situation
            String situation = readInSituation(socket, input).replace(DELIMETER, "\n");
            System.out.println(situation);

            //send option
            Scanner in = new Scanner(System.in);
            System.out.print("Enter option: ");
            out.println(in.nextLine());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static String readInSituation(Socket socket, BufferedReader input) throws Exception {
    while (!input.ready()) {
        Thread.sleep(200);
    }
    return input.readLine();
}

服务器代码更复杂,但它所做的只是响应命令并在屏幕上打印基本文本。

谢谢

【问题讨论】:

    标签: java sockets amazon-web-services timeout client


    【解决方案1】:

    不要在网络上使用PrintWriter,因为它会吞下异常,很可能是之前的“连接重置”。使用BufferedWriter。注意ready() 循环实际上是在浪费时间。

    【讨论】:

      猜你喜欢
      • 2015-03-06
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 2017-04-17
      • 2018-02-18
      • 2022-01-19
      • 2021-01-17
      • 1970-01-01
      相关资源
      最近更新 更多