Showing posts with label timeout. Show all posts
Showing posts with label timeout. Show all posts

Thursday, May 10, 2018

Java WebSocket session times out regardless the value of setMaxIdleTimeout

Leave a Comment

I have the following code (WebSocket server-side endpoint):

@OnOpen public void open(Session session) {     session.setMaxIdleTimeout(-1L);     ... } 

At the client side, I have only:

var websocket = new WebSocket("wss://dummy.org"); websocket.onmessage = onMessage; 

And yet, the session gets closed after 1 or 2 minutes of inactivity. Am I missing something here? Should I tweak something at the client side?

Edit

I also tried at the client side this:

websocket.onclose = reconnect;  function reconnect() {     websocket = new WebSocket("wss://dummy.org");     websocket.onclose = function() {         reconnect();     }; } 

... and (of course) it does not solve the issue.

Edit 2

I also tried to send from the client side a ping message, to which the endpoint responds with a pong message:

(function(){     function sendPing() {         websocket.send("{\"action\":\"ping\"}");         setTimeout(sendPing, 10 * 1000); // 10 seconds.     }      setTimeout(sendPing, 10 * 1000); // 10 seconds. })(); 

1 Answers

Answers 1

There are several things that could end to a closed session.

One reason could be the web-application or container configuration. For example if you use tomcat, check the timeout setting in server.xml file. Or another example is when nGinx is in charge of routing the connection. There are also some configurations on stand-alone websocket servers, depending on your implementation, you might want to check them.

Second reason could be client-side configuration. Do a little search on how to set timeout in your javascript code. There are already many articles and answers about it on internet, I cant provide you one myself. -- you could also test with a java client and see if the problem is from server code or client one. (of course, that also needs some configuration)

Your internet connection (unless you are testing locally) could be next reason for connection failures. Although usually you can recognize this by overriding/adding onError(Exception e).

There is one more thing that you must implement in order to keep websocket connections alive: a heartbeat system. Most standard websocket libraries support ping and pong. On each side (usually server side) you can send ping frames to the other side and they automatically send back a pong frame. This helps keeping connection alive. This method also can help server side realize if the client is actually out there!!!

And as you already said, do not solve your problems by ignoring them. Making an alive and healthy websocket connection takes some effort and a time to deal with many things which by ignoring them you will end up with bigger troubles.

I hope this helps.

Read More

Sunday, March 4, 2018

C++ CInternetSession connexion lost

Leave a Comment

I use CInternetSession to get and post request. But when a connexion time out occurs, I lost the connexion and I always get invalid server request error, I don't understand why. Moreover, there is also a memory leak.

#include "stdafx.h" #include "httpConnexion.h" #include "TSException.h"  ChttpConnexion::ChttpConnexion()     : CInternetSession(AfxGetAppName(), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, NULL, INTERNET_FLAG_DONT_CACHE)     , m_lastRequest() {            SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 10000);     SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, 10000);     m_bAttente = true; }  ChttpConnexion::~ChttpConnexion() { }  std::string ChttpConnexion::sendRequest(const std::string& strUrl) {        DWORD dwServiceType;     CString strServerName;     CString strObject;     INTERNET_PORT nPort;     AfxParseURL(strUrl.c_str(), dwServiceType, strServerName, strObject, nPort);      CString strHeaders = _T("User-Agent: User-Agent=Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\nAccept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7\r\nConnection: keep-alive\r\nContent-Type: application/x-www-form-urlencoded");     CString strTmp = "", strResult = "";     CHttpConnection* pHttpConnexion = NULL;     CHttpFile* pHttpFile = NULL;      try     {            //Creation de la connexion Http         pHttpConnexion = GetHttpConnection(strServerName, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, nPort, NULL, NULL);          //Creation de la requete GET         pHttpFile = pHttpConnexion->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE);          //Envoi de la requéte         BOOL bRequestSend = pHttpFile->SendRequest(strHeaders);          CString headers;headers.Empty();         DWORD dwRet;         pHttpFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF,headers);         pHttpFile->QueryInfoStatusCode(dwRet);          //Lecture du résultat         while ( pHttpFile->ReadString(strTmp))         {             strResult += strTmp;         }          //Fermeture de la requéte         pHttpFile->Close();          //Fermeture de la connexion         pHttpConnexion->Close();          //Suppression des objets         if (pHttpFile != NULL)               delete pHttpFile;          if (pHttpConnexion != NULL)              delete pHttpConnexion;     }     catch(CInternetException* exp)     {         exp->Delete();          //Fermeture de la requéte         if (pHttpFile != NULL)         {             pHttpFile->Close();             delete pHttpFile;         }          //Fermeture de la connexion         if (pHttpConnexion != NULL)          {             pHttpConnexion->Close();             delete pHttpConnexion;         }         throw CTSException("sendRequest");     }            return strResult.GetString(); }   std::string ChttpConnexion::postRequest(const std::string& strUrl, const std::string& postData) {         DWORD dwServiceType;     CString strServerName;     CString strObject;     INTERNET_PORT nPort;     AfxParseURL(strUrl.c_str(), dwServiceType, strServerName, strObject, nPort);      CString strHeaders = _T("User-Agent: User-Agent=Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\nAccept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7\r\nConnection: keep-alive\r\nContent-Type: application/x-www-form-urlencoded");     CString strTmp = "", strResult = "";     CHttpConnection* pHttpConnexion = NULL;     CHttpFile* pHttpFile = NULL;      try     {            //Creation de la connexion Http         pHttpConnexion = GetHttpConnection(strServerName, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, nPort, NULL, NULL);          //Creation de la requete GET         pHttpFile = pHttpConnexion->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject, NULL, 1, NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE);          //Envoi de la requéte          BOOL bRequestSend = pHttpFile->SendRequest(strHeaders, (LPVOID) (LPCTSTR) postData.c_str(), postData.length());          CString headers;headers.Empty();         DWORD dwRet;         pHttpFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF,headers);         pHttpFile->QueryInfoStatusCode(dwRet);          CString data;         GetCookie(strServerName, "sess_id", data);          //Lecture du résultat         while ( pHttpFile->ReadString(strTmp))         {             strResult += strTmp;         }           //Fermeture de la requéte         pHttpFile->Close();          //Fermeture de la connexion         pHttpConnexion->Close();          //Suppression des objets         if (pHttpFile != NULL)               delete pHttpFile;          if (pHttpConnexion != NULL)              delete pHttpConnexion;     }     catch(CInternetException* exp)     {         exp->Delete();          //Fermeture de la requéte         if (pHttpFile != NULL)         {             pHttpFile->Close();             delete pHttpFile;         }          //Fermeture de la connexion         if (pHttpConnexion != NULL)          {             pHttpConnexion->Close();             delete pHttpConnexion;         }         throw CTSException("postRequest");     }         return strResult.GetString(); } 

Thanks for helping!

1 Answers

Answers 1

  • when you construct your object and you call CInternetSession constructor, why the 3rd param is NULL? It should be something like PRE_CONFIG_INTERNET_ACCESS. You may need to use the proxy settings if you are behind a proxy.
  • check the content of strServerName, it may be invalid and GetHttpConnection fails because of that.
  • in your try, you GetHttpConnection and OpenRequest, but you don't check if the results aren't NULL. You only check later (too late) if they aren't NULL to delete them. You should check them after GetHttpConnection and OpenRequest, before using them. (But I guess the exception occurs during GetHttpConnection)
  • if the timeout occurs after 10sec, maybe it's because your timeout is too low (in your constructor).
  • there were some old reports that https may be a problem. But you didn't mentioned what was your request and what you were requesting.
  • in your request header, you are requesting different file formats (xml, html, png, etc...), but you are using a GetString and appending it to a string. If you are getting a binary data, it may not work. You should use a char[] buffer. Check this example.
  • after using your object ChttpConnexion, did you call .Close() on it?

In the end, I would recommend attaching a debugger and put a breakpoint in the catch to see where exactly the error occurs, or add some debug logs. This may help.

Read More

Wednesday, December 20, 2017

Redis::TimeoutError in Rails application

Leave a Comment

I keep getting Redis::Timeout error in my application (both in UI and in background jobs). I am using AWS ElastiCache service for Redis.

This is how I create a Redis connection. In my config/application.rb , I have:

$redis = Redis.new(host: REDIS_HOST, port: REDIS_PORT, db: REDIS_DB) 

How can I avoid getting timeout errors? I am using the default connection settings as follows:

> $redis.client.options[:reconnect_attempts]  => 1  > $redis.client.options[:timeout]  => 5.0  > $redis.client.options[:tcp_keepalive]  => 0  > $redis.client.options[:inherit_socket]  => false 

1 Answers

Answers 1

You should pool your Redis connections with the help of the Connection Pool Gem and increase the timeout value if the problem persists:

ConnectionPool.new(size: 5, timeout: 3) {Redis.new({:host => 'localhost', :port => 6379, :db => 1, :timeout => 240})} 

Redis Gem

Read More

Tuesday, June 13, 2017

How can a slow internet on client side be a reason for server time out exception in asp.net?

Leave a Comment

I have a .Net application up and running.

We have had a fluctuating connection yesterday. While testing in such scenarios we had received multiple server time out exception emails like below.

Server Time Out

Type : System.Web.HttpException, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a  Message : Request timed out. Source : Help link : WebEventCode : 3001 ErrorCode : -2147467259 Data : System.Collections.ListDictionaryInternal TargetSite : HResult : -2147467259 Stack Trace : The stack trace is unavailable. Additional Info: 

IMPORTANT: Above exception occurred while doing a ajax post by a button placed with in update panel.

My question here is why would a slow internet on client side raise such server time out exception?

Isn't server timeout exception is related to such cases where server cannot execute the request in underlying time mention in HttpRuntime setting? May be due to some lengthy operation or some long database execution which takes longer than the time mentioned in setting under HttpRuntime.

If server is not able to connect to the client due to clients fluctuating internet, then Client Disconnected exception would be raised which we did yesterday. But I am not able to conclude the reason for this server timeout exception.

I already know that increasing the execution timeout will fix the issue, but I have to provide technical explanation for the reason as to why such exception of Server Timeout raised.

My best guess here is that the ajax request would be doing some continuous communication with server for executing of single request server and would raise timeout exception if it does not receives some required further communication messages due to client's bad internet. I have search over internet for the same to support my guess but in vain.

Also to provide environmental details, there is a load balancer serving the request.

Any help would be highly appreciated.

1 Answers

Answers 1

It is because (as you write) the connection of client to server is slow, so if the server (or client) sending data to this server, connection can´t handle it, so you get timeout error, because the data can´t been transfered in defined time.

You also write, that this is caused by sending Ajax request, so maybe try to increase execusion timeout in web configuration file (web.config):

<httpRuntime executionTimeout = "number(in seconds)"/> 

enter image description here

More about executionTimeout here and here about Ajax requests.

Read More

Sunday, April 24, 2016

Slack PHP API - Avoid Timeout error

1 comment

I am trying to use Slack Custom command and not pretty sure how to use delayed messages since the Yoda Speak External API takes more than 3 seconds to respond.

I have done the following:

  • Sent the slack command /Yoda in my case and received the reponse_url.
  • Used the following to post the following to the response URL.
$data_string = '{"response_type": "in_channel", "text":"Checking,please wait..."}' ; $chs = curl_init(); curl_setopt($chs, CURLOPT_URL, $response_url); curl_setopt($chs, CURLOPT_POST, true); curl_setopt($chs, CURLOPT_POSTFIELDS, $data_string);  curl_setopt($chs, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($chs, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($chs, CURLOPT_RETURNTRANSFER, true); curl_setopt($chs, CURLOPT_POST, 1); curl_setopt($chs, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); $results = curl_exec($chs); 

enter image description here

  • Now, when I call the Yoda API, it gives the following error "Timeout was reached". I read about delayed responses but not sure how should I proceed from here.
$chsres = curl_init(); curl_setopt($chsres, CURLOPT_URL, "https://yoda.p.mashape.com/yoda?sentence=welcome+to+stack"); curl_setopt($chsres, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($chsres, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($chsres, CURLOPT_VERBOSE, true); curl_setopt($chsres, CURLOPT_TIMEOUT, 45); curl_setopt($chsres, CURLOPT_RETURNTRANSFER, true); curl_setopt($chsres, CURLOPT_HTTPHEADER, array('Content-Type:application/json', "X-Mashape-Key:> deMeGoBfMvmshQSemozTqJEY9z0jp1eIhuAjsnx9cQAQsHUifD")); $resultchsres = curl_exec($chsres); echo $resultchsres; 

Can someone please let me know how to get rid of the timeout error using delayed responses?

UPDATED CODE:

$response_url = $_POST['response_url']; $text = $_POST['text'];  $term = str_replace(' ', '+', $text);  //https://paypal.slack.com/services/B0VQMHX8W#service_setup //initial respond with 200OK for timeout ignore_user_abort(true); set_time_limit(0); ob_start(); echo('{"response_type": "in_channel", "text": "Checking, please wait..."}'); header($_SERVER["SERVER_PROTOCOL"] . " 200 OK"); header("Content-Type: application/json"); header('Content-Length: '.ob_get_length()); ob_end_flush(); ob_flush(); flush();       $chsres = curl_init();     curl_setopt_array($chsres, array(         CURLOPT_URL => "https://yoda.p.mashape.com/yoda?sentence=$term",         CURLOPT_SSL_VERIFYPEER => FALSE,         CURLOPT_SSL_VERIFYHOST => FALSE,         CURLOPT_VERBOSE => true,         CURLOPT_RETURNTRANSFER => FALSE,         CURLOPT_HTTPHEADER => array('Content-Type:application/json', "X-Mashape-Key: deMeGoBfMvmshQSemozTqJEY9z0jp1eIhuAjsnx9cQAQsHUifD"),         CURLOPT_RETURNTRANSFER => true     ));     $yodaresponse = curl_exec($chsres);      $curl = curl_init();     curl_setopt_array($curl, array(         CURLOPT_URL => $response_url,         CURLOPT_POST => 1,         CURLOPT_RETURNTRANSFER => true,         CURLOPT_POSTFIELDS => $yodaresponse     ));      $resp = curl_exec($curl);     var_dump($resp);     curl_close($curl); 

I still get the same error "Darn – that slash command didn't work (error message: Timeout was reached). Manage the command at slash-command"

2 Answers

Answers 1

You're doing all the right things, just need to change the order.

  1. Respond to the original request with a 200 OK response immediately. See this answer for details, but essentially:

    ignore_user_abort(true); ob_start(); echo('{"response_type": "in_channel", "text": "Checking, please wait..."}'); header($_SERVER["SERVER_PROTOCOL"] . " 200 OK"); header("Content-Type: application/json"); header('Content-Length: '.ob_get_length()); ob_end_flush(); ob_flush(); flush(); 
  2. Then make the Yoda API request using curl, as you're doing

  3. Once you have the Yoda results, send them to Slack at $response_url using curl, as you're doing.

Answers 2

From what I can see in the documentation, you're doing things mostly correctly. Just by echoing anything out, you're already passing a 200 OK message, so no need to do it explicitly. You should check to make sure this isn't a server problem though; is the URL being posted to valid? Not getting mangled by a rewrite rule along the way?

I've made some changes to your code below, including some debugging that will go to your error log (i.e. Apache's error log, by default.) Give it a try, and at the very least you'll have some more debugging details.

<?php $response_url = $_POST["response_url"]; $term = rawurlencode($_POST["text"]); error_log("POST: " . print_r($_POST, 1));  ob_end_clean(); ob_start(); $response = ["response_type"=>"in_channel", "text"=>"Checking, please wait..."]; echo json_encode($response); header("Content-Type: application/json"); header("Content-Length: " . ob_get_size()); ob_end_flush(); flush();  $ch = curl_init(); curl_setopt_array($ch, [     CURLOPT_URL => "https://yoda.p.mashape.com/yoda?sentence=$term",     CURLOPT_HTTPHEADER => ["X-Mashape-Key: deMeGoBfMvmshQSemozTqJEY9z0jp1eIhuAjsnx9cQAQsHUifD"],     CURLOPT_RETURNTRANSFER => true ]); $yodaresponse = curl_exec($ch); curl_close($ch); error_log("Yoda response: $yodaresponse");  $yodajson = json_encode([     "response_type"=>"in_channel",     "text"=>$yodaresponse ]); $ch = curl_init(); curl_setopt_array($ch, [     CURLOPT_URL => $response_url,     CURLOPT_POST => 1,     CURLOPT_HTTPHEADER => ["Content-Type: application/json"],     CURLOPT_RETURNTRANSFER => true,     CURLOPT_POSTFIELDS => $yodajson ]);  $resp = curl_exec($ch); curl_close($ch); error_log("API response: $resp"); 
Read More