发送第二条消息时HttpUrlConnection连接重置错误

时间:2018-10-31 11:30:01

标签: java sockets client-server httpurlconnection

仅此而已,服务器已正确接收了发送的第一条消息,但接下来的所有消息均失败。这是循环访问消息并处理调试和代码逻辑错误的主循环。变量udc是我的数据库连接,但工作正常,请忽略它。

for (MessageOutModel message : messageOutModels) {
    HttpURLConnection connection = MakeConnection();
    Date currentMoment = new Date(Calendar.getInstance().getTimeInMillis());
    System.out.println("Sent message id: " + message.id);
    OutputStreamWriter out = new OutputStreamWriter(
            connection.getOutputStream());
    out.write(message.contenido);
    out.close();
    //os.write(message.contenido);
    System.out.println("Message sent");
    int responseCode = connection.getResponseCode();
    System.out.println("Connection message: " + responseCode);
    message.f_ultimo_intento = currentMoment;
    if (responseCode != 200) {
        message.intentos++;
        message.desc_error = "Connection error: " + responseCode
                + " Connection error message: " + connection.getResponseMessage() + "Response error:" +
                connection.getResponseMessage();
       udc.UpdateMessageOut(message);
       if (message.intentos == configModel.n_reintentos) {
           udc.InsertError("MAX_INTENTOS", "Se ha alcanzado el máximo número de " +                         "intentos para el id-ticket: " + message.id + "-" + message.ticket_number);
       }
    } else {
        message.desc_error = "";
        udc.UpdateMessageOut(message);
    }
    connection.disconnect();
}

方法MakeConnection()

protected HttpURLConnection MakeConnection() throws IOException {
    QName q = new QName(SERVER_URL, "");
    URL url = new URL(q.getNamespaceURI() + q.getLocalPart());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("UserName", Username);
    connection.setRequestProperty("PassWord", Password);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.TEXT_PLAIN);
    return connection;
}

Connection reset error

2 个答案:

答案 0 :(得分:0)

将此作为快速解决方案。

HttpURLConnection connection = MakeConnection();

for (MessageOutModel message : messageOutModels) {
  // logic from your sample
}
connection.disconnect();

此外,您可以使用try-with-resources来稍微改善设计。

答案 1 :(得分:0)

最后,这导致客户端和服务器出现防火墙问题。在第一个连接之后,它每隔两次就会阻止连接。