Keep connection alive?

Hi.
I am trying to make a http connection to a site and reuse the connection to fetch several pages.
Here is the code I copied from java.sun.com and modified
import java.net.*;
import java.io.*;
public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL url= new URL("http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html");
        URLConnection conn = url.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                conn.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
            url  = new URL("http://java.sun.com/docs/books/tutorial/networking/sockets/index.html");
        conn = url.openConnection();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
}When I call url.openConnection() again, a new connection is open and assigned to conn.
However, I don't want to have a new connection since the program will be slow if there are a lot of threads are running at the same time....also, there is some overhead time to create a new connection...
Is there anyway to reuse the existing connection?
Thanks.

In 1.4.x (I didn't check the other versions), there is a system property called http.keepAlive (http://java.sun.com/j2se/1.4.2/docs/guide/net/properties.html). By default this property is set to true. This will keep the connection to the server open for a limited time (I think it is in the order of 5 seconds). All this is done underwater in the networking libraries,
You could also checkout http://jakarta.apache.org/commons/httpclient/. It supports keepalive.
Cheers,
--Arnout                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • How to keep connection alive?

    I wondering if there is any way to keep connection alive during some period of inactivity.
    I have the SQL Developer 1.2.1 (it is not easy to update as I have no admin privileges on work computer) under Windows XP, connecting to Oracle9i Enterprise Edition Release 9.2.0.6.0.
    The inconvenience is that the connection become dropped after some inactivity time.
    What I have to do is to disconnect and connect again. But if I run any query in dropped connection condition it would take long time before it come back with a message that there is no connection.
    I could not find any kind of 'stay connected' option. (Like it is in some other application with time set possibility to send a some request to a server just to stay connected (for exm: PuTTY))
    To do it by myself it would be done by having some continuously looping script, that would run some simple select (say, sysdate) periodically, but I do not know if it possible to do it from SQL Developer.
    If it done in PL-SQL, it will be processed in Oracle, not in SQL Developer; so, it is not useful.
    Does anybody have or know any suggestion or advice to keep connection stay active?
    Appreciate any help!
    Alex
    Message was edited by:
    alex5161

    The trouble is shared connections. While the dbms_lock.sleep is sleeping, the connection will be frozen.
    Having said that, the real solution is to fix how sqldeveloper handles lost connections. Session timeouts are usually there for a reason and client software needs to learn to live with it.

  • Please Help - To keep LDAP connection alive

    Hi,
    I have used the below function to communicate with LDAP which I have taken and modified from one of the posts in this forum.
    My issue is, each time the function opens a connection, search and closing the connection and its seriously affects the performance.
    I hope we can resolve this by keeping the connection alive. As I am new to this concept, I am not sure how to do this.
    It would be great, if some one help me to keep the connection alive for the below function. Thanks in advance.
    create or replace FUNCTION <name> (loginname VARCHAR2)
    RETURN NUMBER
    IS
    -- Adjust as necessary.
    l_ldap_host VARCHAR2(256) := '';
    l_ldap_port VARCHAR2(256) := '';
    l_ldap_user VARCHAR2(256) := '';
    l_ldap_passwd VARCHAR2(256) := '';
    l_ldap_base VARCHAR2(256) := '';
    l_retval PLS_INTEGER;
    l_session DBMS_LDAP.session;
    l_attrs DBMS_LDAP.string_collection;
    l_message DBMS_LDAP.message;
    l_filter varchar2(35):='xxxx='|| loginname;
    l_count NUMBER:=0;
    BEGIN
    -- Choose to raise exceptions.
    DBMS_LDAP.USE_EXCEPTION := TRUE;
    -- Connect to the LDAP server.
    l_session := DBMS_LDAP.init(hostname => l_ldap_host,portnum => l_ldap_port);
    l_retval := DBMS_LDAP.simple_bind_s(ld => l_session,dn => l_ldap_user,passwd => l_ldap_passwd);
    -- Get attribute
    l_attrs(1) := 'xxxx';
    l_retval := DBMS_LDAP.search_s(ld => l_session, base => l_ldap_base, scope => DBMS_LDAP.SCOPE_SUBTREE, filter => l_filter, attrs => l_attrs, attronly => 0, res => l_message);
    l_count:=DBMS_LDAP.count_entries(ld => l_session, msg => l_message);
    -- Disconnect from the LDAP server
    l_retval := DBMS_LDAP.unbind_s(ld => l_session);
    return l_count;
    EXCEPTION
    WHEN OTHERS THEN
    dbms_output.put_line('Error :'||SQLERRM);
    return 0;
    END <fun name>;
    Thanks,
    Praveen
    Edited by: 920577 on Mar 13, 2012 9:40 AM
    Edited by: 920577 on Mar 13, 2012 9:41 AM

    The basic template looks as follows:
    SQL> create or replace package Foo as
      2 
      3  procedure LdapLogoff;
      4  function GetData( empName varchar2 )  return number;
      5 
      6  end;
      7  /
    Package created.
    SQL>
    SQL> create or replace package body Foo as
      2 
      3  isLoggedOn boolean;
      4 
      5  procedure LdapLogon is
      6  begin
      7          DBMS_OUTPUT.put_line( '..running logon()' );
      8          isLoggedOn := true;
      9  end;
    10 
    11  procedure LdapLogoff is
    12  begin
    13          DBMS_OUTPUT.put_line( '..running logoff()' );
    14          isLoggedOn := false;
    15  end;
    16 
    17  function GetData( empName varchar2 ) return number is
    18  begin
    19          if not isLoggedOn then
    20                  LdapLogon();
    21          end if;
    22         
    23          DBMS_OUTPUT.put_line( '..running GetData() for '||empName );
    24          return(
    25                  round(DBMS_RANDOM.Value(1,100))
    26          );
    27  end;
    28 
    29 
    30  --// main()
    31  begin
    32          DBMS_OUTPUT.put_line( 'Package Foo loaded into memory' );
    33          isLoggedOn := false;
    34  end;
    35  /
    Package body created.
    SQL>
    SQL>
    SQL> select empno, ename, Foo.GetData(ename) as ID from emp order by empno;
         EMPNO ENAME              ID
          7369 SMITH              23
          7499 ALLEN              47
          7521 WARD               88
          7566 JONES              71
          7654 MARTIN             91
          7698 BLAKE              28
          7782 CLARK              92
          7788 SCOTT              91
          7839 KING               48
          7844 TURNER             89
          7876 ADAMS              64
          7900 JAMES              16
          7902 FORD               18
          7934 MILLER             35
    14 rows selected.
    Package Foo loaded into memory
    ..running logon()
    ..running GetData() for SMITH
    ..running GetData() for ALLEN
    ..running GetData() for WARD
    ..running GetData() for JONES
    ..running GetData() for MARTIN
    ..running GetData() for BLAKE
    ..running GetData() for CLARK
    ..running GetData() for SCOTT
    ..running GetData() for KING
    ..running GetData() for TURNER
    ..running GetData() for ADAMS
    ..running GetData() for JAMES
    ..running GetData() for FORD
    ..running GetData() for MILLER
    SQL>
    SQL> select empno, ename, Foo.GetData(ename) as ID from emp where rownum = 1;
         EMPNO ENAME              ID
          7369 SMITH               9
    ..running GetData() for SMITH
    SQL>
    // call Foo.Logoff manually when done, or leave it to
    // Oracle to close and release resources when the
    // session terminates

  • ADK - Keeping EIS Connections Alive

    Hi,
              I am using the ADK that comes with WL 8.1 SP3. The challenge I am facing is to keep my connections alive while there is no activity (at the TCP/IP socket level) between the app server and the EIS.
              The EIS closes any sockets after 30 minutes of inactivity causing the connections to go into CLOSE_WAIT state.
              Is there any method I can use within the connector to keep pinging the server and make sure these connections have TCP/IP traffic?
              Has anyone used the <test-frequency-seconds> weblogic-ra.xml? What is its purpose? pinging?
              Appreciate your insight..

    Hi
              I have a requirement, which is some what similar to what is mentioned above.
              I too have to ping the interface at regular intervals to keep the connection alive. I also assumed that, we can use the test-frequency-seconds attribute. But for that to work, we have to implement the interface, http://java.sun.com/j2ee/1.4/docs/api/javax/resource/spi/ValidatingManagedConnectionFactory.html, which is there only from weblogic 9.
              But since our client is using weblogic 8.1, we are tied to that version.
              Can anyone please assist in solving this.

  • Keep wifi connection alive

    Hi. I've noticed that after moving from opensuse to arch, my wifi connection dies on me after inactivity. I've tried this workaround:
    * Add a crontab to ping a website every 15 minutes. I'm using this command:
    * ping -c 4 www.google.com
    However, the connection still dies. Is there a better way to keep my connection alive? Perhaps if I increase the number of packets?

    As per this ubuntu forum post, I found something that might do the trick
    http://ubuntuforums.org/showthread.php?t=420959
    Adapted to arch, this may work:
    #!/bin/sh
    HOST=www.google.com
    ping -c 1 -W 10 $HOST &>/dev/null
    if [ $? -eq 0 ]; then
    #ping is ok
    exit
    else
    #first try
    ifconfig wlan0 down
    sleep 3
    ifconfig wlan0 up
    sleep 10
    ping -c 1 -W 10 $HOST &>/dev/null
    if [ $? -eq 0 ]; then
    exit
    else
    #second try
    /etc/rc.d/wlan restart
    /etc/rc.d/network restart
    iwconfig wlan0 essid NOAH_S_ARK
    sleep 10
    ping -c 1 -W 10 $HOST &>/dev/null
    fi
    fi
    The corresponding root crontab entry to run it every 20 minutes is
    */20 * * * * <nameofscript>
    Gonna try when I get home.

  • Keep JDBC connection alive

    Hi,
    I am running into problem with JDBC connection outside of the firewall. The firewall disconnect idle connection after 15min. Is there a way to keep JDBC alive for
    as long as the application is running?
    Thanks,

    Notwithstanding connection pools generally managed by an application server, I would not advocate keeping a connection open beyond the immediate need for it. Certainly there is a performance cost to open a connection and that must be weighed against the potential for orphaned resources by leaving a connection in a trapped state. Personally I have never found an overriding NEED to keep a connection open beyond the method where the connection was first opened.
    Using a connection pool makes the cost even less to open and release connections on an as needed basis.
    Just my 2 krupplenicks worth, your mileage may of course vary.
    PS.

  • Mail.app keeping IMAP connections alive and active

    Hi all,
    I was having some issues with the MySQL databases on my website, so I gave my hosting provider a call.
    It seems that Mail.app is opening up an IMAP process for each of my 24 e-mail accounds, and keeping it alive for as long as Mail is running. According to the representative I spoke with, e-mail clients, even with IMAP should start a process, synchronize the mail, and close the process, and all of this should happen in around 0.2 seconds.
    The problem is that there is a cap of 20 processes on my hosting server, so Mail's behavior is basically causing lots of problems - as long as mail is open and all of my accounts are enabled, my website can't access my MySQL databases.
    Does anyone know of a solution to this problem? I used to have "Automatically synchronize mailboxes checked" and tried unchecking this for troubleshooting purposes, but the same thing still happens.
    Any ideas or suggestions will be very appreciated.
    Thanks!

    From what I've read, imap is designed to create a persistent connection, and keep it open until you quit the program.
    But there's another problem which might be getting in your way: mail.app does indeed create persistent connections, but then rather than re-using them, it seems to open another new persistent connection each time it checks the mail. So the processes never close, and they start to pile up as new ones are added.
    What's more, mail opens multiple connections per account. Looks like it opens 4 connections to check each separate account, and those all get left open until you quit the program.
    The reason they do this is, so they say, "performance". More connections = faster mail. But it's a real headache when it doesn't close old processes before opening new ones.
    Also an option to limit the number of connections made per account would be welcome.
    Thunderbird does exactly the same thing, by the way.

  • Freeware utilities for keeping network connection alive?

    Hi, I am wondering if anyone has recommendations for a freeware utility that can keep the network connection alive on my 2010 mac mini.
    Already have sleep, screen saver, and password lock turned off.  Also using static IP.
    When it sits for a while I can no longer ping it from my PC workstation or use iTunes, VNC etc from my phone.
    When I open up the mac, which I am using as HTPC, it will connect right away to Google etc using Safari yet it has dropped the share connection to my PC.
    Thanks!  Sean

    Thanks for the report!

  • Socket - keep it alive or reconnect every time you need it?

    Hello, there.
    What would be the better approach for using the Sockets in AS3.
    1st) open one connection and keep it alive until the site unloads?
    2nd) open a connection, use it, and close it when done; then, open again when I need?
    Considering a scenario where some users will make a constant use of the Socket, but others will almost not use it, what would be the better approach? Does an alive Socket connection use too much bandwidth? Does the action of connecting consumes more than keeping it alive? What is your opinion?
    Thank you all!
    CaioToOn!

    I think that kind information  is inposible to be get because it depends of internet connection. From some users the time will be less from the other users.
    Also keep alive msg may depend from protocol and my be only one Byte sendend on every 15 sek ( for example )

  • App to remember wireless logins, or keep them alive?

    Given the number of wireless access points that are set up with an authentication screen, either as amenities (my grocery store makes me accept their TOS for free wireless) or security (my university uses a Bluesocket gateway) and the fact that my phone grabs those "known" networks automagically, is there a keychain app that will remember the login info for me or, at least, something I can install that will keep a data connection alive to those networks so that I don;pt have to authenticate every single time I wake up the phone?
    I know it's possible to put a MAC filter into many of these devices to bypass the registration screen, but that's not really feasible everywhere from the position of an end-user...

    For your BlueSocket hotspot...
    http://melloware.com/products/bluesocket/
    BlueSocket Authenticator is intended for people who roam on wireless networks with BlueSocket authentication. Many businesses and universities use BlueSocket and it can be extremely frustrating to have to open a web browser and log in every time a valid user wants to use the wireless network. Especially on the iPhone/iPod Touch because you have to re-authenticate every time the device goes to sleep for longer than 15 minutes.
    The purpose of this program is simple: One-click authentication to BlueSocket enabled networks.

  • IPad / iPhone ios 6 needs "keep network alive" option.

    I know this has been discussed in other posts, but a change occured from iOS 5 to iOS 6 where the network connection is no longer maintained after the screen goes to the lock screen.  I use my iPad at my place of work and always have it upright so I can see any new emails / push notifications that come through.  The screen turning on and showing the message is a nice alert to let me know I need to look at my email etc.  This has been working ever since I have had my iPad 3rd generation until I updated to iOS 6.  The device loses the internet connection so no more alerts come through.  VERY frustrating.  I have the latest version of iOS 6 and this issue hasn't been addressed and doesn't look like it will be addressed in the forthcoming 6.1 update. 
    I understand the need to preserve battery life, so this may not be desired functionailty for many.  PLEASE give us the option to keep WiFi alive if there are no plans to put it back to the functionailty of ios5.  Thanks for the ear.
    -Mark

    Try #5.
    Some things to try first:
    1. Turn Off your iPad. Then turn Off (disconnect power cord for 30 seconds or longer) the wireless router & then back On. Now boot your iPad. Hopefully it will see the WiFi.
    2. Go to Settings>Wi-Fi and turn Off. Then while at Settings>Wi-Fi, turn back On and chose a Network.
    3. Change the channel on your wireless router (Auto or Channel 6 is best). Instructions at http://macintoshhowto.com/advanced/how-to-get-a-good-range-on-your-wireless-netw ork.html
    4. Go into your router security settings and change from WEP to WPA with AES.
    5.  Renew IP Address: (especially if you are droping internet connection)
        •    Launch Settings app
        •    Tap on Wi-Fi
        •    Tap on the blue arrow of the Wi-Fi network that you connect to from the list
        •    In the window that opens, tap on the Renew Lease button
    ~~~~~~~~~~~~~~~~~~~~~~~~~
    iOS 6 Wifi Problems/Fixes
    Fix For iOS 6 WiFi Problems?
    http://tabletcrunch.com/2012/09/27/fix-ios-6-wifi-problems/
    Did iOS 6 Screw Your Wi-Fi? Here’s How to Fix It
    http://gizmodo.com/5944761/does-ios-6-have-a-wi+fi-bug
    How To Fix Wi-Fi Connectivity Issue After Upgrading To iOS 6
    http://www.iphonehacks.com/2012/09/fix-wi-fi-connectivity-issue-after-upgrading- to-ios-6.html
    iOS 6 iPad 3 wi-fi "connection fix" for netgear router
    http://www.youtube.com/watch?v=XsWS4ha-dn0
    Apple's iOS 6 Wi-Fi problems
    http://www.zdnet.com/apples-ios-6-wi-fi-problems-linger-on-7000004799/
    ~~~~~~~~~~~~~~~~~~~~~~~
    Look at iOS Troubleshooting Wi-Fi networks and connections  http://support.apple.com/kb/TS1398
    iPad: Issues connecting to Wi-Fi networks  http://support.apple.com/kb/ts3304
    WiFi Connecting/Troubleshooting http://www.apple.com/support/ipad/wifi/
    How to Fix: My iPad Won't Connect to WiFi
    http://ipad.about.com/od/iPad_Troubleshooting/ss/How-To-Fix-My-Ipad-Wont-Connect -To-Wi-Fi.htm
    iOS: Connecting to the Internet http://support.apple.com/kb/HT1695
    iOS: Recommended settings for Wi-Fi routers and access points  http://support.apple.com/kb/HT4199
    How to Quickly Fix iPad 3 Wi-Fi Reception Problems
    http://osxdaily.com/2012/03/21/fix-new-ipad-3-wi-fi-reception-problems/
    iPad Wi-Fi Problems: Comprehensive List of Fixes
    http://appletoolbox.com/2010/04/ipad-wi-fi-problems-comprehensive-list-of-fixes/
    Fix iPad Wifi Connection and Signal Issues  http://www.youtube.com/watch?v=uwWtIG5jUxE
    Fix Slow WiFi Issue https://discussions.apple.com/thread/2398063?start=60&tstart=0
    How To Fix iPhone, iPad, iPod Touch Wi-Fi Connectivity Issue http://tinyurl.com/7nvxbmz
    Unable to Connect After iOS Update - saw this solution on another post.
    https://discussions.apple.com/thread/4010130
    Note - When troubleshooting wifi connection problems, don't hold your iPad by hand. There have been a few reports that holding the iPad by hand, seems to attenuate the wifi signal.
    ~~~~~~~~~~~~~~~
    If any of the above solutions work, please post back what solved your problem. It will help others with the same problem.
     Cheers, Tom

  • Ok I am having issues with my HP Enby 100 D410. Need help setting up eprint, and keeping connected.

    I opened up my printer, set it up, connected.  But I cant seem to keep connected.  I have an eprint email address set up, but the printer reset and now wants me to set up an new eprint using a different code.  How do I get the [email protected] email back.  It says "someone already has address..."  duh, that's me..!  This printer has been more than frustrating.  HP support says open 7 days a week, 24 hours a day.  But when I call, they are closed and only open during certain days and hours... why advertise differently?  I also cannot seem to get my printer to align the printer cart.. stops halfway.  Need this to test scanner.  Anyone with helpful advice?

    Hey mwright286!
    Sorry to hear you're having a problem with your Envy and ePrint! Let me see if i can address the issues you brought up here. HP support for printers is 24x7, if you are receiving a message otherwise you may be dialing the wrong number or selecting the wrong options through the prompts.
    As for the ePrint issue you're having, if the printer's Web services has somehow been reset and the printer gave you a new code to setup ePrint with, unfortunately that address is not available again for 6 months. Make sure you don't turn web services off and then back on unless necessary as this will reset the email address.
    If your printer is having alignment issues though, it is very possible that there is a hardware problem with the printer. Try following this document. If you are still having trouble with the alignment then you will want to call support at 1-800-hpinvent.
    Hope this helps!
    If I have solved your issue, please feel free to provide kudos and make sure you mark this thread as solution provided!
    Although I work for HP, my posts and replies are my own opinion and not those of HP.

  • N85- keeps connecting itself to the Internet

    Hello!
    My phone (N85) keeps connecting itself to the internet every minute or so.
    This is driving me crazy cause I don't have a data plan.
    So I had to check my phone every minute and disconnected the Internet.
    Now I'm back home and it keeps connecting itself to WLAN.
    What should I do?!
    'Thanks in advance! :'(
    Solved!
    Go to Solution.

    Actually, if you just remove the mobile network access point your phone will only be able to connect to WLAN and so no connection when out of range from your network at home.
    First select the offline profile, then delete the mobile data access point in Tools > Settings > Connection > Destinations
    Click on the blue Star Icon below if my advice has helped you or press the 'Accept As Solution' link if I solved your problem..

  • Ipod just keeps connecting/disconnecting. any thoughts?

    here's the story. my ipod died. i upgraded to itunes 7. still was not working, i go to apple and get a refurbished one. the new one keeps connecting/disconnecting. when i open my computer, it shows it just blinking like its there, then its not. does not show in itunes, but half the time says do not disconnect.
    here's where it gets weird. the USB port runs other devices fine. i plugged my ipod into a friends PC and could put music on it. i plugged my friends ipod into my PC and it shows up fine. i've swapped the ipod USB cord with my friend and it still does the same thing. so its not the ipod, its not my comp. and its not my itunes. anyone even want to attempt? i'm at my wits end here.

    Try forcing the iPod into Disk Mode using the instructions in this Apple support document.
    Putting iPod into Disk Mode
    If you can successfully do that, it should keep the iPod mounted on your PC long enough for you to perform a restore of it via iTunes.
    Restoring iPod to factory settings
    B-rock

  • Ipod keeps connecting then disconnecting

    I've tried everything possible to try to make my Ipod mini work. I can't connect it to the PC because it keeps connecting and disconnecting repeatedly. I can't restore it since I can't connect it. I've tried all the different USB ports and I've installed and uninstalled all the programs a few times. I've also reset it connected and disconnected. It has worked before but now it won't! This is driving me nuts

    Similar problem here too plus when I do manage to get them to connect they will not charge.
    Both my classic iPods work fine, in all my computers, and show that they are charging, but my family have 3 nanos, a 4th and two 5ths. Although they all connect to my PC and my laptop fine, none of these will connect correctly to my daughters PC no matter what USB port I put them in.
    I have checked in device manager that the ports are powered (500ma) and nothing else is there to infringe on this supply. Still these items connect and disconnect constantly. Ironically every now and then, they will connect and allow me to look at the files etc in iTunes. I have at one point had two nanos and my classic connected to her computer and they all worked fine for about an hour, I thought that I had finally got rid of the problem but one by one the nanos started to play up again so this exacerbates the problem somewhat.
    I also get various warnings when the Nanos are trying to connect like, software driver failure to install, it will work faster in a high speed USB port, nano needs formatted to work in windows plus a host of others. When I plug them back into my PC they connect fine, so that all adds to the confusion. If this was one nano I would suspect that it was faulty but it is three different ones.
    I have done the 5 Rs, I have even gone as far as upgrading from XP to Windows 7, I have plugged the units into every USB port, I even bought a new PCI/USB card and tried that and still this problem persists.
    I would like to hear from someone with any suggestions as to what is causing this and how to fix it.

Maybe you are looking for