How to keep the connection alive?

Hello! Happy new year!
I have to write an HTTP server that comunicates with many clients in the same time,but keeps the connection with a client open if there the corresponding header is Keep-Alive. I have used threads,and I've tested my program in the following way: I've requested the one page of the site and then I've followed a link from that page. I expected that the broowser and the server talk to the same thread every time,but it seems that they don't. The code I've written is:
//HTTPServer class
ServerSocket serverSocket = null;
        boolean listening = true;
        try {
            serverSocket = new ServerSocket(80);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 80.");
            System.exit(-1);
        while (listening)
              new HTTPMultiServerThread(serverSocket.accept()).start();
//HTTPMultiServerThread
public void run() {
     //     System.out.println(socket.toString());
          try {
while(!serverSocket.isClosed())){
              DataOutputStream out = new DataOutputStream(socket.getOutputStream());
              DataInputStream in = new DataInputStream( socket.getInputStream());
              int nrBytes = in.available();
              if(nrBytes > 0){
                   byte[] bytes = new byte[nrBytes];
                   in.read(bytes);
                   System.out.println("Procesez mesajul:" + nrBytes + new String(bytes));
                   HTTPMessage processedMess = new HTTPMessage(bytes).processMessage();
                   System.out.println("Inchid conexiunea.");
                    log("log.txt", new HTTPMessage(bytes).getStatusLine() + " " + new Data().getCurrentTime());
               //send the message   
out.write(processedMess.getBytes(),0,processedMess.getBytes().length);
                   /* inchid conexiunea
              else{
                   String ret = new String("HTTP/1.1 500 Internal Server Error\n");
                    ret += "Host: cristi\n";
                  ret += "Date: " + new Data().getCurrentTime()+"\r\n";
                  ret += "\r\n";
                  ret += "<html><body><p>HTTP/1.1  500 Internal Serve Error</p> </body><html>\r\n";
                  out.write(ret.getBytes());
              out.close();
              in.close();
                   if(new HTTPMessage(bytes).getHeaderValue("Connection").equals("Close"))
              socket.close();
     }//end while
          } catch (IOException e) {
              e.printStackTrace();
    }I would also like to know how many clients are waiting to be served,in order to develop statistics about the server response time. 10X

hi
same to u .
i think what i get from ur code that ....
use some vector at the server side and whenever any client is connected (offcourse first time or not (depend on u !!)) create an object corresponding(generally created by server for every client) ..
save this in the vector .. and pass it the size of vector to the client with the response .
may this help u .
regards
akash
Indiagames Ltd
[email protected]
India

Similar Messages

  • How to keep the connection to oracle db open  ?

    Hi
    I wrote a function that execute an oracle stored procedure , the function run for 400K times ,
    right now i open connection on every time the function called .
    the function called by another application ,
    can i create a connection that will be open just one time ?
    thank in advance ,
    rami .

    rami4tis wrote:
    Hi
    I wrote a function that execute an oracle stored procedure , the function run for 400K times , You call a db proc 400k times? You probably should look into not doing that.
    right now i open connection on every time the function called .
    the function called by another application ,
    can i create a connection that will be open just one time ?
    If not a pool than the class that does the 400k should have a Destroy/Close method that the caller would be responsible for calling when they are done.

  • How to keep NetStream.Connect alive even when noone is connected?

    is there any timeout set for NetStream.Connect? I am having an issue when one streamer goes to 2way channel and waits for another party to join but after about 1 minute (if noone is receiving that streamer signal) the NetStream.Connect.Close event is fired up. I want to be able to wait little bit longer.
    Any help much appreciated.

    Dear Alll,
    Please help.

  • 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.

  • How to keep the internet connection alive?

    Hi, I am a new Macbook user and everytime my computer goes to screen saver or sleep mode it keeps losing the internet connection. Is this normal? Is anyway to keep the internet alive even is the computer goes to "sleep mode"?
    I mean, it is quite a pain to keep signing in at messenger everytime I wake up my computer or come back from screen saver
    Thank you

    I do not know of a way. When your computer goes into sleep mode, it basically shuts itself down and stores everything in memory. Nothing is moving or working because the whole point of sleep mode is to conserve the battery. If it is really bothering you, go into System Preferences and change the amount of time it takes for the computer to go to sleep.

  • How to determine the connection time?

    Hello!
    We have big troubles with our ConnectionPool. We have adapted most parts from the Book "Professional Java Server Programming" (Wrox Press).
    However, the connections are invalid (I/O Exceptions like "End of TNS Data Channel" or "Broken Pipe") after a while.
    The average up-time of our pool is approximately 24 hours.
    Now we want to drop renew the connections after a certain amount of time (let�s say 1 hour). To do this, we would need to determine the time when the connection has been established. How can this be done?
    I have looked into the DatabaseMetaData class, but did not find anything (at the first glance).
    PLEASE help me / us, the problem is really severe!
    Thanks in advance,
    Gregor Graf

    PLEASE help me / us, the problem is really severe!Where did you get the pool from? Is it your code? If so then are you sending a keep alive query - which would keep the connection active?
    If it isn't your code then are you explicitly returning the connections to the pool?
    Commercial pools don't typically drop connections. Some do which can be discovered by examining the configuration options for the pool that you have.
    If it is your code and you just want to add this, then you add a time value to each connection node. Each time a node is returned you set the time. You have a thread that runs and checks the time value, dropping any that are older than the value you want.

  • Apple TV won't stay on file sharing, can anyone explain how to keep it connected ??

    Having problems keeping Applet TV connected for file sharing, Will disconnect in the middle of watching a movie. Can anyone help
    and tell me how to keep the two devises communicating??

    Is it just when streaming photos or using home-sharing in general? Check istumbler (netstumbler for windows) to check interference. Also check firewall and anti-virus (if applicable), restart router/make sure it's up to date.

  • Everything I own (iPad, iPhone, mac) is set up on wi-fi.  when i bring my work computer home (dell laptop), I cannot get it to keep the connection in a different room. All my other devices work.... does anybody know what i am doing wrong? please help!

    Everything I own (iPad, iPhone, mac) is set up on wi-fi.  when i bring my work computer home (dell laptop), I cannot get it to keep the connection in a different room. All my other devices work.... does anybody know what i am doing wrong? please help!

    Windows drivers for Intel wireless cards are known problematic.. If you have plenty of signal and it still cannot keep or hold the connection the issue can simply be the type of wireless.
    Another problem is using names that windows does not easily handle.
    eg If you set the TC using apple names, like
    Fred Blog's Airport Time Capsule wireless24ad12
    Then to windows this is too long.. it has spaces and it has illegal character.
    Change all names on the TC to suit windows. Short, no spaces and pure alphanumeric.
    Also security must be suitable.. I have no idea how old or what OS your dell is, but if you still have issues.. pull off the security on the TC for a test.. if the computer suddenly works, it is not compatible with WPA2 AES. Make sure you also use a password that is mix upper and lower case plus numbers.. avoid special characters and make it 10-20 characters long say.. it is not required to be more than that unless you are paranoid.

  • How to keep the MB powered on with Lid closed

    How to keep the MB powered on with Lid closed and no monitor connected?

    You can't. And you shouldn't due to heating issues.
    There are however 'hacks' that allow you to bypass
    this.
    http://www.alxsoft.com/mac/sleepless.html
    http://semaja2.net/insomniaxinfo/
    Blackbook C2D   Mac OS X
    (10.4.10)   120Gig, 1Gig, Superdrive.
    This may be true of overheating, but ONLY in the iBooks and very old laptops, if you think about it what is the difference between native clamshell mode (Using the monitor/keyboard etc) and the hacked clamshell mode? does plugging a screen in to the laptop some how create more ventilation :S
    This rumor is really really wrong, and as stated only affected the old machines which were not capable of native clamshell mode, but of course we keep the warnings there because we dont want to be sued if some idiot places it in there laptop bag while rendering a movie.
    PS. If anyone can give me evidence to prove otherwise i will add it to the investigation that im slowly compiling to "bust" this annoying myth

  • Possible to attach an Interactive pdf to DPS ? ( & Keep the interactivity alive )

    Hi,
    Is it possible to open an interactive pdf from an DPS app and keep the interactive alive
    ( buttons /textboxses /submit / send to email ) ?
    I know how to make an zip-folder and link to the document form a button ( HTMLResources/filename.pdf )
    But the pdf is flatten , and the document is useless for my purpose.
    It would be great if this worked, and Adobe DPS could be even more handy than it is to day
    I know it's also possible to import html to indesign, and I have tried to make a form in Dreamwaver.
    The form looks nice on the Ipad & the buttons/ text fields works. But when I press submit ( mailto url )  the email opens.. But no data follows.
    ( Might be something wrong with the form of course )
    If I could link to Adobe Reader ( where the document already exist ) from the DPS-app.. that could be an solution/ and the interactivity works in Reader..
    But I haven't found any way to do that.
    My wish for the DPS of the future is that it would be more like MUSE. More options/ menus and no coding
    If someone have any good ideas on this issue, please let me know.

    Hi, after my first post in this issue I have solved the problem my self.
    The answer is to use Dreamweaver.
    1. Create an form with all the information you need in Dreamweaver. Be aware of the pixel value of the form, should not be larger than the Ipad
    Import the HTML into Indesign (Object /import HTML )
    If the form is larger than the Ipad - You can resize the imported html "frame" and use scale to fit in the web content menu.
    But in this way you don't have 100 % control of what your doing.
    After you imported the code in Indesign, and used the settings you like in web Content ( Folio Overlays ) Upload the DPS article as usual.
    2. Another way is to create an HTML article, where you import a folder with all files the form consist of ( Pictures, CSS and the HTML form  )
    A lot more you can do in this way like dropdown menues, fading images ++ . But is a bit more complicated workflow. So go for nr. 1

  • 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.

  • Keeping the connection open while in sleep

    I was just wondering if there is anyway to keep the internet connection open while the computer is in sleep mode? I have looked around for a little bit but I figured someone else probably already has an answer.
    Just to clarify I don't mean closing the laptop but just putting it into sleep mode. I've read you can't keep a connection open while the laptop is closed but I was wondering if there was a difference between putting it to sleep and closing the laptop.
    Message was edited by: Boogie Chillen

    No difference. If you need to keep the connection open, which is what I do, then set the Energy Saver to never sleep.

  • How to keep the WBS & Order in account assignment tab of SD contract item?

    Hi Experts,
    If I remove the plant from the shipping tab in the contract item (the contract type is WV), I will be able to enter the WBS or Order in accounting assignment tab. However, if I enter the plant (in order to determine the tax in pricing), the WBS and Order are disappered and there is one new settlement rule button showed up.
    Do you know any configuration could keep the WBS and order in the accounting assigment tab even the plant is there.
    Thanks in advance!
    Norman

    Hi Chandra,
    Thanks for your answer. However, I even added the plant in the WBS, the tax (we use tax jurisdiction) still could not be determined.
    The problem is that SAP changes the account assignment tab screen (it suppresses the WBS and Order fields, but addes settlement rule) with the plant in the shipping tab. Do you know how to keep the same account assignment tab screen with the plant in the shipping tab?
    Thanks,
    Norman

  • How to determine the connection string to a SQLite database, in C# code

    Hello. I'm trying to figure out how to specify the connection string to a SQLite database, I would like to access using the following code:
    string connectionString = null;
    SqlConnection connection;
    SqlCommand command;
    SqlDataAdapter adapter = new SqlDataAdapter();
    DataSet ds1 = new DataSet();
    string sql = "SELECT DataName, Data, Id, UserId, DateLastUpdated FROM MainTable";
    connectionString = "Data Source=C:\\SQLITEDATABASES\\SQLITEDB1.sqlite;Version=3;";
    connection = new SqlConnection(connectionString);
    try
    connection.Open();
    command = new SqlCommand(sql, connection);
    catch
    The value I assigned to the variable connectionString, in the code above, I obtained somewhere from the Internet. It does not work. I'm using Visual Studio 2013, against the file sqlite-netFx451-setup-bundle-x86-2013-1.0.96.0.exe, which
    I installed, and got from
    here.
    My application's App.config file looks as follows:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    <configSections>
    </configSections>
    <connectionStrings>
    <add name="DC_Password_Saver.Properties.Settings.DC_Password_SaverConnectionString" connectionString="data source=&quot;C:\Users\patmo_000\Documents\Visual Studio 2013\Projects\DC Password Saver\DC Password Saver\DC Password Saver.db&quot;" providerName="System.Data.SQLite.EF6"/>
    </connectionStrings>
    <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
    </startup>
    </configuration>
    I tried to use the value assigned to connectionString in the XML settings above, replacing single backslash characters with double backslash characters, because the Visual Studio editor flagged them as unrecognizable, and wound up with the
    following.
    SqlDataAdapter adapter = new SqlDataAdapter();
    DataSet ds1 = new DataSet();
    string sql = "SELECT DataName, Data, Id, UserId, DateLastUpdated FROM MainTable";
    connectionString = "data source=&quot;C:\\Users\\patmo_000\\Documents\\Visual Studio 2013\\Projects\\DC Password Saver\\DC Password Saver\\DC Password Saver.db&quot;";
    connection = new SqlConnection(connectionString);
    The above code however does not work either. So again, does anyone know how I can specify in C# code, a connection string to access my SQLite database? Thanks in advance for your reply.

    What does SQLite connection strings has to do with WPF?
    You will find some valid connection strings here:
    https://www.connectionstrings.com/sqlite/
    But you cannot use the SqlConnection class to connect to a SQLite database. You will need to download and add a reference to the System.Data.SQLite library and then use the SQLiteConnection class:
    connection = new System.Data.SQLite.SQLiteConnection(connectionString);
    try
    connection.Open();
    command = new System.Data.SQLite.SQLiteCommand(sql, connection);
    catch
    Please refer to the following article for more information and an example of how to connect and read and write data from an SQLite database using C#:
    http://blog.tigrangasparian.com/2012/02/09/getting-started-with-sqlite-in-c-part-one/.
    There is contains a link where you can download the required assemblies.
    Hope that helps.
    Please remember to mark helpful posts as answer to close your threads and then start a new thread in an approproate forum if you have a new question.

Maybe you are looking for