node.js访问数据库Handshake inactivity timeout

图片说明

访问数据库采用连接池的方法,
node.js版本是v6.9.1,

wampserver的mysql版本:5.6.17;
node的mysql版本:2.12.0

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
node.js安装成功运行失败?

![图片说明](https://img-ask.csdn.net/upload/201606/11/1465618258_685340.png)

node.js的函数问题 急求

function add(domanName,name,email,age,click){ var website=[]; website[0]=domainName; website[1]=name; website[2]=email; website[3]=age; website[4]=click; return website; } 急求这句话是什么意思呢? 是不是函数返回的结果,返回到数组里?这样函数add 的结果就跟数组建立了联系?

如何在不先单击的情况下自动记录用户会话

<div class="post-text" itemprop="text"> <p>I made a site that is user-based and so far I've been able to easily handle the sessions up to this point. I'm not a noob when it comes to php, but I don't have a good working knowledge of javascript. I have set a timeout for my users so that they are automatically timed out after 20 minutes of <em>inactivity</em>. It works great, other than they need to click a link or refresh in order for the session to actually be timed out. This is my current php timeout.</p> <pre><code>&lt;?php //TIMEOUT AFTER 20 MINUTES if(isset($_SESSION['signed_in'])) { $inactive = 1200; if(isset($_SESSION['timeout']) ) { $session_life = time() - $_SESSION['timeout']; if($session_life &gt; $inactive) { $id = $_SESSION['user_id']; //this db row is solely to display # of users logged in mysqli_query($connect, "UPDATE users SET user_signedin='0' WHERE user_id = '$id'"); session_destroy(); $_SESSION = array(); header("Location: timedout.php"); } } $_SESSION['timeout'] = time(); } ?&gt; </code></pre> <p>But I've also tried javascript (setting the timer to 5 minutes) like so:</p> <pre><code>&lt;script&gt; var wintimeout; function SetWinTimeout() { wintimeout = window.setTimeout("window.location.href='timedout.php';",300000); } $('body').click(function() { window.clearTimeout(wintimeout); //when user clicks remove timeout and reset it SetWinTimeout(); }); SetWinTimeout(); &lt;/script&gt; </code></pre> <p>I've searched a number of different places to find out how to implement an automatic redirect without having to click or refresh, but so far no luck. How do people redirect automatically (without clicking or refreshing) upon timeout?</p> <p><strong>EDIT:</strong> For people who are looking for the same answer: Ok, I was able to get the desired effect by adding this to my page header</p> <pre><code>&lt;?php if(isset($_SESSION['signed_in'])) { ?&gt; &lt;meta http-equiv="refresh" content="1800;url=internal.php" /&gt; ?&gt; </code></pre> <p>"internal.php" is very similar to the first piece of code I pasted above, though I've taken out the piece where it checks for timeout. However, now I'm having problems with people exiting the tab and not getting signed out, but that's a whole other issue. </p> </div>

Mousemove和按键无法正常工作

<div class="post-text" itemprop="text"> <p>I am trying to make an auto-logout on inactivity using JavaScript. The thing is even when I move my mouse and rapidly press any key the timer does not reset.</p> <pre><code>var timeOut; function reset() { window.clearTimeout(timeOut); timeOut = window.setTimeout( "redir()" , 5000 ); } function redir() { window.location = "index.php?page=Logout"; } window.onload = function() { setTimeout("redir()" , 5000 ) }; window.onmousemove = reset; window.onkeypress = reset; </code></pre> </div>

CloseableHttpClient 4.5.2如何设置等待超时?

CloseableHttpClient 4.5.2中执行response = httpClient.execute(httpPost); 没有任何的等待效果,直接返回无连接,如果我想让他保持请求30秒是否可以? ``` RequestConfig defaultRequestConfig = RequestConfig.custom(). setConnectTimeout(30000).setConnectionRequestTimeout(30000) .setSocketTimeout(30000).build(); // CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build(); CloseableHttpResponse response = null; String resultString = ""; HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); httpPost.setConfig(defaultRequestConfig); String uuid=UuidUtil.getuuid(); PgmsDao pgms=new PgmsDao(); LoginUI login=(LoginUI) FacesUtil.getSessionMapValue("loginUI"); String netid=login.getLdapuser().getNetid(); String request_user=login.getLdapuser().getName(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String request_date = sdf.format(new Date()); Map<String,String> request_map=(Map)new JSONObject().fromObject(json); String action=request_map.get("action"); response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); String response_date = sdf.format(new Date()); Map<String,String>result=(Map)new JSONObject().fromObject(resultString); String status=result.get("status"); ``` 如果是别的版本也可以,请大佬指点

在laravel 5中,在会话超时时重定向到特定路由

<div class="post-text" itemprop="text"> <p>In the session.php file under Config directory of laravel 5.1, I have specified <code>'lifetime' =&gt; 10</code> which logout the user after 10 minutes of inactivity. But it does not redirect to login page automatically when the session expires until the user clicks on some link.</p> <p>I want to redirect the user to the login page instantly after the session expire even if no link is clicked. I also want to get some values in the session before resetting it.</p> </div>

YII - 对会话过期执行控制器操作

<div class="post-text" itemprop="text"> <p>I am trying to update one column in DB during user session timeout, I have been set the timeout in main.php,</p> <pre><code>'components' =&gt; array( 'session'=&gt;array( 'class'=&gt;'CDbHttpSession', 'timeout'=&gt;10, )), </code></pre> <p>Now the application gets logout automatically after 10 seconds of inactivity, how can i perform some controller action on default Yii session time-out method (which class or method that performs default session expiry in Yii) ?</p> </div>

#mins不活动后自动注销用户

<div class="post-text" itemprop="text"> <p>i have a client side jquery script that logs the user off after 5 mins of inactivity. The problem is though is the user navigates away without logging out the session stays active. If the user closes the browser shouldnt that destroy the session since sessions stay alive for the duration of the browsers being open or the user logs off? </p> <p>anywho this is what i have </p> <pre><code>(function($){ $(document).bind("idle.idleTimer", function(){ document.location = "orders.php?action=logoff&amp;session=timeout"; }); //var minute = 60000; //1 minute is 60,000 miliseconds. var minute = 300000; //5 minutes var timeout = minute; $.idleTimer(timeout); })(jQuery); </code></pre> <p>how can i implement a server side if the user navigates away? I was thinking of using cron but then that would be not the right way (im thinking but then maybe im wrong)</p> <p>i read this post <a href="https://stackoverflow.com/questions/3068913/user-inactivity-logout-php">User Inactivity Logout PHP</a></p> <p>and i don't see how the session can still take effect if the user navigates away</p> </div>

将时间存储在DB中并在登录PHP后恢复

<div class="post-text" itemprop="text"> <p>We already know that the following code in PHP will log the user out after 5 mins of inactivity. </p> <pre><code>$timeout = 5*60; // Set timeout minutes $logout_redirect_url = "index.php"; // Set logout URL if (isset($_SESSION['start_time'])) { $elapsed_time = time() - $_SESSION['start_time']; if ($elapsed_time &gt;= $timeout) { session_unset(); session_destroy(); header("Location: $logout_redirect_url"); } } $_SESSION['start_time'] = time(); </code></pre> <p>I want to implement a modification of the current code and do something like this:</p> <ul> <li>Assume the user logs out when he had 3 minutes left before automatic logout(assuming the time doesn't restart for him after his inactivity for 2 minutes), we keep track of the time he has left by storing it in a DB (MySQL) and later on start reducing from the same 3 minutes after he logs back in. How can i do this? </li> </ul> </div>

会话不存在时如何从数据库中删除数据 - PHP

<div class="post-text" itemprop="text"> <p>I'm developing a chat module for my application...</p> <p>1) I'm opening a window for users to chat, is there way that when users close the chat window, I can update status of that record...i mean event for the closed browser ?</p> <p>2) I know that default session time is 24mins, so after 24mins of inactivity, user will be kicked out from the site and will asked to loggin once again.</p> <p>How to delete/flush the data in my database, when user has no activity for 24mins(when user is logged out from the session due to inactivity)</p> </div>

关于安卓zxing项目的使用问题

用了两份zxing模块,一份保留了完整功能作为依赖库,一份是精简版放在主程序模块中,我的构想是主界面有扫码识别、历史记录、分享等功能,还有个跳转的次界面的功能是个数据库的增删查改,使用精简版zxing用于扫码直接输出结果到一个EditView框中方便操作。 代码基本实现,build没有问题,但是run就出问题了,虚拟安卓设备一直显示xx已停止运行,run的错误如下: ``` E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.zxingdemo, PID: 1969 java.lang.RuntimeException: Unable to resume activity {com.example.zxingdemo/com.google.zxing.client.android.CaptureActivity}: java.lang.ClassCastException: com.karics.library.zxing.view.ViewfinderView cannot be cast to com.google.zxing.client.android.ViewfinderView at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3645) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3685) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2898) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) Caused by: java.lang.ClassCastException: com.karics.library.zxing.view.ViewfinderView cannot be cast to com.google.zxing.client.android.ViewfinderView at com.google.zxing.client.android.CaptureActivity.onResume(CaptureActivity.java:162) at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1354) at android.app.Activity.performResume(Activity.java:7079) at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3620) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3685)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2898)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)  at android.os.Handler.dispatchMessage(Handler.java:105)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6541)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)  I/InactivityTimer: Finishing activity due to inactivity Application terminated. ``` **萌新求解,,,**

WordPress(最新)和Joomla 1.5之间的单点登录(SSO)

<div class="post-text" itemprop="text"> <p>I am after a plugin to create a single sign on between Joomla 1.5 and WordPress (latest) . It must do the following:</p> <p>Synch users from Joomla to WP (username, first name, last name, email, password). When you login to WP - automatically login to Joomla. When you logout from WP - automatically logout from Joomla. When you login to Joomla - automatically login to WP. When you logout from Joomla - automatically logout from WP. Set a session inactivity logout.</p> <p>tried one plugin and its not solving my problem</p> <p>Synch users from Joomla to WP (username, first name, last name, email, password). When you login to WP - automatically login to Joomla. When you logout from WP - automatically logout from Joomla. When you login to Joomla - automatically login to WP. When you logout from Joomla - automatically logout from WP. Set a session inactivity logout.</p> </div>

too long

<div class="post-text" itemprop="text"> <p>I have downloaded doctrine 2.2 orm. I have gone through its installation guide but i cant properly understand its documentation. Can someone guide me through the setup process of doctrine. I have previously been working with Hibernate ORM framework in java. They have excellent documentation which are easy to understand for beginners. I dont find the documentation of doctrine to be of that level. Can somebody provide some sample projects on doctrine to begin with?</p> </div>

jQuery Ajax事件绑定

<div class="post-text" itemprop="text"> <p>I am using the <a href="https://github.com/ehynds/jquery-idle-timeout" rel="nofollow">https://github.com/ehynds/jquery-idle-timeout</a> to produce a Mint style idle timer which performs an Ajax call to a 'keep-alive' page.</p> <p>I also have a piece of Javascript for Ajax form submits that pops up a 'Please wait' message to alert the user that activity is occurring though the pages isn't loading. </p> <p>For some reason the toggleAjaxLoader() function is getting bound to the ajax:before and ajax:complete events each time the keep alive page is polled. I do not want this as it is confusion to the user. Why would this be binding to the idletimeout and/or how can I drill into what is happening?</p> <p>Loading animation:</p> <pre><code>// Toggles our animated ajax loader image function toggleAjaxLoader() { jQuery('#ajax_loader').toggle(); } </code></pre> <p>Idle timeout:</p> <pre><code>/* * Inactivity notifier and auto logout */ jQuery(function(){ var redirectToURL = getAbsoluteUrl('/logout/auto=true'); // URL to relocate the user to once they have timed out var keepAlive = getAbsoluteUrl('/keep-alive'); if (jQuery("#idletimeout").length) { $.idleTimeout('#idletimeout', '#idletimeout a', { idleAfter: 2700, // 45 minutes warningLength: 60, // number of seconds to wait before redirecting the user keepAliveURL: keepAlive, AJAXTimeout: 2500, pollingInterval: 5, // 60 expiredMessage: 'Your session has expired. You are being logged out for security reasons.', // message to show user when the countdown reaches 0 onTimeout: function(){ $(this).slideUp(); window.location.replace(redirectToURL); }, onIdle: function(){ $(this).slideDown(); // show the warning bar }, onCountdown: function( counter ){ $(this).find("span").html( counter ); // update the counter }, onResume: function(){ $(this).slideUp(); // hide the warning bar // Tums.bump_tums_session(session[:user].session['sessionGuid']); } }); }; }); </code></pre> </div>

不活动和登录系统PHP

<div class="post-text" itemprop="text"> <p>I am trying to create a system where, when the user is inactive for x amount of time, they should are logged out and sent back to 'index.php'. I am using the code I found here - <a href="http://cookbooks.adobe.com/post_Set_a_time_limit_on_a_login_session__PHP_-16701.html" rel="nofollow noreferrer">http://cookbooks.adobe.com/post_Set_a_time_limit_on_a_login_session__PHP_-16701.html</a> and I put it in a function like this:</p> <p>phpfunc/inactivity.php</p> <pre><code>&lt;?php function inactivity() { // create a session if (!isset($_SESSION)) { session_start(); } // store the current time $now = time(); // get the time the session should have expired $limit = $now - 60*20; // check the time of the last activity if (isset ($_SESSION['last_activity']) &amp;&amp; $_SESSION['last_activity'] &lt; $limit) { // if too old, clear the session array and redirect $_SESSION = array(); header('../index.php'); exit; } else { // otherwise, set the value to the current time $_SESSION['last_activity'] = $now; } } ?&gt; </code></pre> <p>Then, I call the function like this...at the top of my protected page </p> <p>templates/login_success.php:</p> <pre><code>&lt;?php require('/Users/Eamon/Sites/phpfunc/inactivity.php'); inactivity(); if($_SESSION['username'] === null){ header("location: ../index.php"); } ?&gt; &lt;h1&gt;Login Successful&lt;/h1&gt; &lt;h2&gt;Username: &lt;? echo $_SESSION['username']?&gt;&lt;/h2&gt; &lt;div id="logoutlinkdiv" &gt; &lt;a href = "#" &gt;Log out&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I can login - and all the inactivity stuff seems to work. I tested it by adding a few echo statements here and there...and after login I tried going to the protected page - like this "localhost/~Eamon/templates/login_success.php" and it lets me see it...after 20 minutes I have to sign in again. However, I have a page that loads once the user logs out (after clicking the "logoutlinkdiv" link) - and it has a link on it to log in again. When I click this link, I get the message "Wrong Username or Password" - which can be found in the below file (which gets executed upon login). After 20 more minutes, I can login again without getting this error.</p> <p>checklogin.php</p> <pre><code>&lt;?php session_start(); $host="localhost"; // Host name $username="root"; // Mysql username $password="bonjour3"; // Mysql password $db_name="itit"; // Database name $tbl_name="members"; // Table name // Connect to server and select databse. $mysqli = new mysqli("$host", "$username", "$password", "$db_name")or die("cannot connect"); // Define $myusername and $mypassword $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; $sql = $mysqli-&gt;prepare("SELECT * FROM $tbl_name WHERE username=? and password=?"); $sql-&gt;bind_param('ss',$myusername,$mypassword); $sql-&gt;execute(); $sql-&gt;store_result();//apply to prepare statement $numRows = $sql-&gt;num_rows; if($numRows === 1){ $_SESSION['username'] = $myusername; } else { echo "Wrong Username or Password"; session_destroy(); } ?&gt; </code></pre> <p>Here is the aforementioned logout page (where the user can login again...the trouble page!):</p> <p>templates/logout.php</p> <pre><code>&lt;?php session_start(); session_destroy(); ?&gt; &lt;div id="loginlinkdiv" &gt; &lt;h2&gt;You have been logged out.&lt;/h2&gt; &lt;a href = "#"&gt;Log in&lt;/a&gt; &lt;/div&gt; </code></pre> <p>In case it is relevant...here is the jquery I am using. I am making an SPA - so jquery is loading and emptying things for me in the "main" div on index.php - here:</p> <p>index.php</p> <pre><code>&lt;?php session_start(); ?&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;it IT&lt;/title&gt; &lt;script src="reqscripts/jquery.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="js/application.js" type="text/javascript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="main"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>UPDATE</strong></p> <p>Following the suggestion - I tried the first answer on this page:</p> <p><a href="https://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes">How do I expire a PHP session after 30 minutes?</a></p> <p>I changed two files.</p> <p>phpfunc/inactivity.php now looks like this:</p> <pre><code>&lt;?php function inactivity() { if (isset($_SESSION['LAST_ACTIVITY']) &amp;&amp; (time() - $_SESSION['LAST_ACTIVITY'] &gt; 1800)) { // last request was more than 30 minutes ago session_unset(); // unset $_SESSION variable for the run-time session_destroy(); // destroy session data in storage header("/Users/Eamon/Sites/index.php"); } $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp } ?&gt; </code></pre> <p>and templates/login_success.php looks like this:</p> <pre><code>&lt;?php require('/Users/Eamon/Sites/phpfunc/inactivity.php'); session_start(); inactivity(); ?&gt; &lt;h1&gt;Login Successful&lt;/h1&gt; &lt;h2&gt;Username: &lt;? echo $_SESSION['username']?&gt;&lt;/h2&gt; &lt;div id="logoutlinkdiv" &gt; &lt;a href = "#" &gt;Log out&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Still the same problem appears to be happening...and I think I caught a new glitch. When I click the login link (templates/logout.php) it brings me to index.php. I try to login, but the information in the textboxes gets reset, and seemingly nothin happens. When I try again - I get "Wrong Username or Password" again. Also - <code>&lt;? echo $_SESSION['username']?&gt;</code> is not showing up on the login_success.php page anymore.</p> <p><strong>UPDATE</strong></p> <p>It seems as if I'm not getting signed in because <code>&lt;? echo $_SESSION['username']?&gt;</code> still doesnt output anything.</p> </div>

如何增加cakephp 2的登录时间

<div class="post-text" itemprop="text"> <p>Can you please let me know how to increase the session expiry time for CakePHP 2?</p> <p>Currently, i set the configuration as bellow.</p> <pre><code>Configure::write('Session', array( 'defaults' =&gt; 'php', 'timeout' =&gt; 129600, // The session will timeout after 30 minutes of inactivity 'cookieTimeout' =&gt; 129600, // The session cookie will live for at most 24 hours, this does not effect session timeouts 'ini' =&gt; array( 'session.gc_maxlifetime' =&gt; 129600 // 36 hours ) )); </code></pre> <p>But, these settings not work and session expired in almost 24 minutes.Thanks This thread didn't solve my problem "<a href="https://stackoverflow.com/questions/30694932/how-to-increase-cakephp-auth-component-session-expire-time">How to increase cakephp Auth component session expire time</a>"</p> </div>

成功登录IE后,不能打开页面

<div class="post-text" itemprop="text"> <p>I installed Booked software in wampserver and made necessary changes in config.php.</p> <p>If I open the index page and login, it's redirecting to dashboard.php, but the screen remains in index.php</p> <p>All other browsers are redirecting to next page except IE. I found the problem also. </p> <p>If I remove localhost/Web from script.url settings and make it http:// then its working fine in IE.</p> <p>If it's http: then After submitting a reservation it fails to load the homepage instead it loads like this <a href="http://localhost/dashboard.php/localhost/dashboard.php" rel="nofollow">http://localhost/dashboard.php/localhost/dashboard.php</a> which results to an error page.</p> <p>My config.php</p> <pre><code>$conf['settings']['app.title'] = 'Booked Scheduler'; $conf['settings']['default.timezone'] = 'America/Chicago'; $conf['settings']['allow.self.registration'] = 'true'; $conf['settings']['admin.email'] = 'admin@example.com'; $conf['settings']['admin.email.name'] = 'Booked Administrator'; $conf['settings']['default.page.size'] = '50'; $conf['settings']['enable.email'] = 'true'; $conf['settings']['default.language'] = 'en_us'; $conf['settings']['script.url'] = '**http://localhost/Web'; $conf['settings']['image.upload.directory'] = 'Web/uploads/images'; $conf['settings']['image.upload.url'] = 'uploads/images'; $conf['settings']['cache.templates'] = 'true'; $conf['settings']['use.local.jquery'] = 'false'; $conf['settings']['registration.captcha.enabled'] = 'true'; $conf['settings']['registration.require.email.activation'] = 'false'; $conf['settings']['registration.auto.subscribe.email'] = 'false'; $conf['settings']['registration.notify.admin'] = 'false'; $conf['settings']['inactivity.timeout'] = '30'; $conf['settings']['name.format'] = '{first} {last}'; $conf['settings']['css.extension.file'] = ''; $conf['settings']['disable.password.reset'] = 'false'; $conf['settings']['home.url'] = ''; $conf['settings']['logout.url'] = ''; $conf['settings']['default.homepage'] = '1'; </code></pre> <p>Any suggestions to resolve this?</p> <p>Note:Registration page is working perfectly in IE</p> <p>Thanks in advance.</p> </div>

更改数据库中的客户端数据而不刷新页面

<div class="post-text" itemprop="text"> <p>I have a user system and I use cookies to make them automatically logout after 1 hour of inactivity, but only if the client refresh the page it would update the database row. This is my code so far:</p> <pre><code>if(isset($_SESSION['username'])) { $activeUser = $_SESSION['username']; if(isset($_COOKIE['active'])) { setcookie('active', $activeUser, time() +3600); } else { $makeOffline = $DB-&gt;query("UPDATE users SET user_loggedin = '0' WHERE user_id = '".$dbid."'"); header("location: ".$site_url."/logout.php"); } } </code></pre> <p>What I'm asking now is if there's any way I could set <code>user_loggedin</code> to 0 after 1 hour of inactivity without that the client have to refresh the page?</p> </div>

如何在http下载上实现不活动超时

<div class="post-text" itemprop="text"> <p>I've been reading up on the various timeouts that are available on an http request and they all seem to act as hard deadlines on the total time of a request.</p> <p>I am running an http download, I don't want to implement a hard timeout past the initial handshake as I don't know anything about my users connection and don't want to timeout on slow connections. What I would ideally like is to timeout after a period of inactivity (when nothing has been downloaded for x seconds). Is there any way to do this as a built in or do I have to interrupt based on stating the file?</p> <p>The working code is a little hard to isolate but I think these are the relevant parts, there is another loop that stats the file to provide progress but I will need to refactor a bit to use this to interrupt the download:</p> <pre><code>// httspClientOnNetInterface returns an http client using the named network interface, (via proxy if passed) func HttpsClientOnNetInterface(interfaceIP []byte, httpsProxy *Proxy) (*http.Client, error) { log.Printf("Got IP addr : %s ", string(interfaceIP)) // create address for the dialer tcpAddr := &amp;net.TCPAddr{ IP: interfaceIP, } // create the dialer &amp; transport netDialer := net.Dialer{ LocalAddr: tcpAddr, } var proxyURL *url.URL var err error if httpsProxy != nil { proxyURL, err = url.Parse(httpsProxy.String()) if err != nil { return nil, fmt.Errorf("Error parsing proxy connection string: %s", err) } } httpTransport := &amp;http.Transport{ Dial: netDialer.Dial, Proxy: http.ProxyURL(proxyURL), } httpClient := &amp;http.Client{ Transport: httpTransport, } return httpClient, nil } /* StartDownloadWithProgress will initiate a download from a remote url to a local file, providing download progress information */ func StartDownloadWithProgress(interfaceIP []byte, httpsProxy *Proxy, srcURL, dstFilepath string) (*Download, error) { // start an http client on the selected net interface httpClient, err := HttpsClientOnNetInterface(interfaceIP, httpsProxy) if err != nil { return nil, err } // grab the header headResp, err := httpClient.Head(srcURL) if err != nil { log.Printf("error on head request (download size): %s", err) return nil, err } // pull out total size size, err := strconv.Atoi(headResp.Header.Get("Content-Length")) if err != nil { headResp.Body.Close() return nil, err } headResp.Body.Close() errChan := make(chan error) doneChan := make(chan struct{}) // spawn the download process go func(httpClient *http.Client, srcURL, dstFilepath string, errChan chan error, doneChan chan struct{}) { resp, err := httpClient.Get(srcURL) if err != nil { errChan &lt;- err return } defer resp.Body.Close() // create the file outFile, err := os.Create(dstFilepath) if err != nil { errChan &lt;- err return } defer outFile.Close() log.Println("starting copy") // copy to file as the response arrives _, err = io.Copy(outFile, resp.Body) // return err if err != nil { log.Printf(" Download Copy Error: %s ", err.Error()) errChan &lt;- err return } doneChan &lt;- struct{}{} return }(httpClient, srcURL, dstFilepath, errChan, doneChan) // return Download return (&amp;Download{ updateFrequency: time.Microsecond * 500, total: size, errRecieve: errChan, doneRecieve: doneChan, filepath: dstFilepath, }).Start(), nil } </code></pre> <p><strong>Update</strong> Thanks to everyone who had input into this.</p> <p>I've accepted JimB's answer as it seems like a perfectly viable approach that is more generalised than the solution I chose (and probably more useful to anyone who finds their way here). </p> <p>In my case I already had a loop monitoring the file size so I threw a named error when this did not change for x seconds. It was much easier for me to pick up on the named error through my existing error handling and retry the download from there. </p> <p>I probably crash at least one goroutine in the background with my approach (I may fix this later with some signalling) but as this is a short running application (its an installer) so this is acceptable (at least tolerable)</p> </div>

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

springboot+jwt实现token登陆权限认证

一 前言 此篇文章的内容也是学习不久,终于到周末有时间码一篇文章分享知识追寻者的粉丝们,学完本篇文章,读者将对token类的登陆认证流程有个全面的了解,可以动态搭建自己的登陆认证过程;对小项目而已是个轻量级的认证机制,符合开发需求;更多精彩原创内容关注公主号知识追寻者,读者的肯定,就是对作者的创作的最大支持; 二 jwt实现登陆认证流程 用户使用账号和面发出post请求 服务器接受到请求后使用私...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

早上躺尸,晚上干活:硅谷科技公司这么流行迟到?

硅谷科技公司上班时间OPEN早已不是什么新鲜事,早九晚五是常态,但有很多企业由于不打卡,员工们10点、11点才“姗姗来迟”的情况也屡见不鲜。 这种灵活的考勤制度为人羡慕,甚至近年来,国内某些互联网企业也纷纷效仿。不过,硅谷普遍弹性的上班制度是怎么由来的呢?这种“流行性迟到”真的有那么轻松、悠哉吗? 《动态规划专题班》 课程试听内容: 动态规划的解题要领 动态规划三大类 求最值/计数/可行性 常...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大胆预测下未来5年的Web开发

在2019年的ReactiveConf 上,《Elm in Action》的作者Richard Feldman对未来5年Web开发的发展做了预测,很有意思,分享给大家。如果你有机会从头...

立即提问
相关内容推荐