A new socket for every http-request?

Do I have to make a new socket for every http-request? The code below doesn't work because it is two requests in a row. The first GET works, but the second doesn't. I thought that the purpose of a socket is that you set it up once and then you should be able to do arbitrary communication between the two peers. Maybe that is just the case with sockets only but not if you use sockets to perform http.
Thank you for your answers! Nice greetings from Austria (not Australia)!
Stefan :)
package httptest;
import javax.net.ssl.*;
import java.io.*;
import java.net.*;
public class Conn2 {
    private PrintWriter out;
    private BufferedReader in;
    private Socket socket;
    public Conn2()
        try {
         socket = new Socket("www.google.at", 80);
         out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));         
         if (out.checkError())
          System.out.println("SSLSocketClient:  java.io.PrintWriter error");
         in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println("Connect erfolgreich.");
     } catch (Exception e) {
         System.err.println(e);
    public void test()
        String inputLine;
        // 1. GET
        out.println("GET / HTTP/1.0");
     out.println();
     out.flush();
     try
            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
        catch(IOException e)
            System.err.println(e);
        // 2. GET
        out.println("GET / HTTP/1.0");
     out.println();
     out.flush();
        try
            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
        catch(IOException e)
            System.err.println(e);
}

Normally in the HTTP protocol, the server will close the connection after every request. So after you do the first GET, the server sends you the result and closes the connection. You have to open a new connection for the second GET.
You can set specific headers to keep the connection open, which makes things faster if you have to do multiple GET's quickly after another. Lookup the specification of the HTTP protocol on http://www.ietf.org/
Maybe it's easier to use a HTTP client library like Apache's HTTPClient: http://jakarta.apache.org/commons/httpclient/ so that you don't have to implement all the difficulties of the HTTP protocol yourself.

Similar Messages

  • New HttpSession object every HTTP request

    I am having a weird problem where the Tomcat server gives out a new session cookie every request, so all my JSPs have a new, empty session every time they run, so I can't store anything!
    I have set up the following little test JSP:
    <%
    Date created = new Date(session.getCreationTime());
    Date accessed = new Date(session.getLastAccessedTime());
    int i = session.getMaxInactiveInterval();
    out.println("ID " + session.getId() + "<br>");
    out.println("timeout: " + i + "<br>");
    out.println("Created: " + created + "<br>");
    out.println("Last Accessed: " + accessed + "<br>");
    %>
    And it gives a different session ID, and new session creation time every
    time I refresh the page.
    The web.xml has a session timeout of 1 hour.
    But 2 consecutive refreshes get:
    ID 9A74C902F25A33B61DAB7CDCA1C0FD57
    timeout: 3600
    Created: Mon Jun 09 14:49:35 BST 2003
    Last Accessed: Mon Jun 09 14:49:35 BST 2003
    follwed by:
    ID 30AFCD9986223FF0B9E502C2D8D6724C
    timeout: 3600
    Created: Mon Jun 09 14:49:49 BST 2003
    Last Accessed: Mon Jun 09 14:49:49 BST 2003
    Of course this is screwing me up because I want to store things in the
    session context! Can anyone help???
    Thanks,
    Nige

    Cookies are enabled. I have snooped at the HTTP traffic, and the last session cookie that the server sent is returned by the browser in every request. The server then spews out a new one when it replys!
    I'm using Tomcat 5.
    I'll try downloading the latest release of V4.
    Cheers,
    Nige

  • New instance for every request to Servlet

    I want to create new instance for every request to Servlet ...
    I am running my servlet on weblogic

    Hi!
    what functionality can there be that has to be put into init()?
    Another idea:
    why not include your needed functions in a private method within the servlet and call this method from init() and from doPost/doGet so it is processed any time the servlet is called?
    btw: more instances of the same servlet seems to me as going back to the roots (cgi).
    Thomas.

  • Session replication at every http request

    Hi everybody
    I'm trying to use ZKoss Framework (www.zkoss.org) to develop a
    web application and deploy it in a Clustered WebLogic Server.
    The main issue I'm facing is that the "state" of the visual interface
    is stored inside the http session, and so, when node that handle
    the http request changes, the state is resetted and then the page changes,
    even if there was no user intervention.
    So I need to replicate the whole session at every http request,
    to prevent strange behaviours when the request handler node's changes.
    Do you know some settings that will force WebLogic Server to replicate the whole
    session at every http request?
    Thanks in advance.
    bye.

    Hi Marco,
    Yes, You are right But You NEED NOT to put setAttribute("key","value")...code in all your JSPs. because if the Attribute data of Session is changed then Automatically it will be replicated (only the Changed Data and not the Data which is unchanged). Even we need not to worry about replicating the Unchanged Data Again...And WebLogic will take care of ChangedData by itself. There is no other alternate solution available in weblogic to do this...Even no such similar Element available in Deployment descriptors as well.
    Actual Link is Broken http://download-llnw.oracle.com/docs/cd/E13222_01/wls/docs90/cluster/failover.html
    Any way i am copy-pasting few Lines from E-Docs (the actual link i am not able to find ..but may be u can open the cached page:
    http://74.125.153.132/search?q=cache:bxTbqJEsQTsJ:download-llnw.oracle.com/docs/cd/E13222_01/wls/docs90/cluster/failover.html+setAttribute+Session+replication+weblogic&cd=6&hl=en&ct=clnk&gl=in
    ---------------------------If you are not able to open the link then please refer to the E-Docs copy-paste content below --------------------------
    Programming Considerations for Clustered Servlets and JSPs
    This section highlights key programming constraints and recommendations for servlets and JSPs that you will deploy in a clustered environment.
    Session Data Must Be Serializable
    To support in-memory replication of HTTP session states, all servlet and JSP session data must be serializable.
    Note:     Serialization is the process of converting a complex data structure, such as a parallel arrangement of data (in which a number of bits are transmitted at a time along parallel channels) into a serial form (in which one bit at a time is transmitted); a serial interface provides this conversion to enable data transmission.
    Every field in an object must be serializable or transient in order for the object to be considered serializable. If the servlet or JSP uses a combination of serializable and non-serializable objects, WebLogic Server does not replicate the session state of the non-serializable objects.
    Use setAttribute to Change Session State
    In an HTTP servlet that implements javax.servlet.http.HttpSession, use HttpSession.setAttribute (which replaces the deprecated putValue) to change attributes in a session object. If you set attributes in a session object with setAttribute, the object and its attributes are replicated in a cluster using in-memory replication. If you use other set methods to change objects within a session, WebLogic Server does not replicate those changes. Every time a change is made to an object that is in the session, setAttribute() should be called to update that object across the cluster.
    Likewise, use removeAttribute (which, in turn, replaces the deprecated removeValue) to remove an attribute from a session object.
    Note:     Use of the deprecated putValue and removeValue methods will also cause session attributes to be replicated.     
    Thanks
    Jay SenSharma
    Edited by: Jay SenSharma on Feb 11, 2010 10:24 PM
    Edited by: Jay SenSharma on Feb 11, 2010 10:26 PM

  • Notes in Mail: Every time I type a new note it is emailed to my Mail along with a new note for every change I make to it

    Notes in Mail: Every time I type a new note it is emailed to my Mail along with a new note for every change I make to it.
    I don't mind the Note being updated in my mail but I don't need a new copy every time I edit/add to the note.
    It's driving me mad!
    Thanks.

    A new tab opens by default as a blank tab (about:blank).
    If that isn't the case then an extension has changed that behavior.
    * https://support.mozilla.com/kb/Troubleshooting+extensions+and+themes

  • Creating listener for incoming http requests

    Hi,
    I am trying to create a server for incoming http requests.
    I am using Connector.open("socket://:5555") call to bind to the server socket.
    I have give permission for Connector.socket, as well as Connector.http to this application.
    The server is able to accept connections when the client connects using socket://localhost:5555, but does not accept any incoming connection when the client connects using http://localhost:5555.
    How can I create a service on my mobile which will accept http requests.
    Thanks,
    Debashis

    Allistair,
    One thing that might help you is an understanding of the Oracle database JVM architecture. Here's a DOC which you might find interesting:
    http://otn.oracle.com/products/oracle8i/pdf/Oow_BestPractices.pdf
    Hope this helps,
    -Dan
    http://www.compuware.com/products/devpartner/db/oracle_debug.htm
    Debug PL/SQL and Java in the Oracle Database

  • "A new folder for every project file"

    Aha!!  Right, from now on ... (thanks Steve)
    From the Muvipix.com Guide to Adobe PE11 by Steve Grisetti
    (p 36) [on starting and saving a new project]
    2     Click the Browse button to choose a location to save your new
    project file.
    We at Muvipix recommend always selecting the Browse option and,
    wherever you choose to save your file, creating a new folder for every
    new project file.
    This little bit of housekeeping keeps all of your new project's files in
    one neat, little folder. And, when your project is done and you want to
    clear it from your computer, you can then remove not only the project
    file but all of the temp, render and scratch disk files Premiere Elements
    has created for that project simply by deleting that single folder!
    This makes post-project clean-up a much easier and neater process.
    OK, hope I've got it this time (at last)
    cheers
    Brian

    Oh no!  I thought I’ll re-work that Canal video again, but this time saved the project from the very start in a new folder on an ext HD (500 GB) connected USB3.0.  Tried all sorts of things on it, saved each time in the same folder.   Cleared all 14 clips from Project Assets (which of course emptied the timeline).   Shut down PE11.   Checked via Windows Explorer that the project files were all on the ext HD – and by the way, there are no other files on it, just the PE files.  My understanding is that Advanced System Care Pro (Iobit) regularly defrags all my drives if necessary (tho’ I haven’t done this manually for months with this drive).
    OK, opened PE, went to Open Recent Projects, it shows the above .prel file and the entire path, I click on it and – 
    Weird, just weird
    Nil desperandum
    Brian
    Edited --- and another weird thing, my email isn't sending the complete message I type to this forum.   I sent a whole message once and it never appeared, but this time it's cut off half a sentence above (it did this before, earlier today).
    That sentence should read,
    OK, opened PE, went to Open Recent Projects, it shows the above .prel file and the entire path, I click on it and – nothing happened!   (You'll have gathered that's what happened, but I wrote it in my Windows Live Mail, sent via BT-Yahoo ISP ......... )  Hey wait, there was a whole lot more.
    Here's a copy / paste from Windows Live Mail outbox
    It’s so odd, because as I said previously, most of the time it works so well, does all the things it’s supposed to do.   I followed Steve’s instructions here to the letter.   By the way, as you know, it’s not just the ext HD, this has been happening all along with allowing PE to save everything in its default Folder 11.
    I would be – now – very sorry indeed to have to abandon PE11 simply on this account, but it’s causing me to waste such a lot of time.   (Let alone the expense of buying it, plust one Lynda.com course, plus 2 books – not forgetting that I’d previously tried the Corel software and bought a book and DVD for that too!!)
    Might just use – what’s that simplicity-itself thingy everyone uses who just want to get any old kind of thing up on You Tube ..........   Oi vey!! <<more weary sigh>>
    Weird, just weird
    Nil desperandum

  • How to generate a new rhread for every request

    Hello,
    I'm trying to write a server side program that does the following, recieves a Single connection from a client, client sends a request to the server side program, the server side program sends to a third party(back end) and waits for a reply.
    The problem i am facing is the following, I want to for each message(request) recieved from the Client to generate a new thread and establish a new connection with the third party, I have tried creating a new thread for the communication with the third party, in this case if the response from backend takes time I will still be able to recieve other requests from the client. But I dont know how to return the message that his been to the Father thread. The reason why I am doing this is that I dont want the same thread that recieves the request from client to wait until the reply for the previous thread is sent.
    Here's the code which I have been trying to implement.
    ClientCommunicator {
    Socket soc= new Socket(IPAddress,port);
    Thread backEndComm= new Thread (new BackEndCommunicator
    (soc,"Message To Back End"));
    backEndComm.setPriority(8);
    backEndComm.start();
    public class BackEndCommunicator implements Runnable
    Socket socket;
    String messageToBeSentToBE= "";
    public BackEndCommunicator(Socket socket, String messageTOBE)
    this.socket= socket;
    messageToBeSentToBE= messageTOBE;
    public void run()
    PrintWriter outtBackEnd= null;
    BufferedReader innBackEnd= null;
    String replyFromBE= "";
    try
    outtBackEnd= new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    outtBackEnd.println(messageToBeSentToBE);
    outtBackEnd.flush();
    innBackEnd= new BufferedReader(new InputStreamReader(socket.getInputStream()));
    replyFromBE= innBackEnd.readLine();
    How can I return the String "replyFromBE" to the ClientCommunicator class so it can be sent to the client as soon as recieved from the back end.
    regards,
    [email protected]

    I assume the problem you are having is that your ClientCommunicator thread is blocking in a read and has no way of receiving notification from the other thread. Seems like you have a couple options at least.
    1. Use non-blocking IO and a selector to do service both the client socket and the backend socket. Usually, NIO is more of a pain than it is worth unless you need to service hundreds of connections at once, but I think that in this case where you know that there are only two connections it might be easy enough to use.
    2. A second option would be to avoid blocking on the read by using the available method on the input stream to first determine if you can actually read anything. This would allow you to wait with a small timeout on a monitor that the backend communicator could notify when it receives a response. This is not the ideal solution because you are limiting how fast you respond to the client and could be using more cpu time than necessary. However, it might be a lot easier to implement and could be adequate for what you need.
    First solution is more elegant but potentially not worth the trouble. Second solution is less elegant, but may be good enough.

  • When my swf in a html page connected with a socket server other http requests were blocked, how to resolve?

    I have used php to write a socket server(text chat server),
    then I use xmlsocket to write a client, I put this swf file in my html page, erverything of this client swf were ok: ervery clients could send or receive messages, but the other http request in this html page was unable to send(or receive) data from webserver,
    webserver and chat server were on the same server,
    and I have tried to use socket to instead if xmlsocket in my flash, but the new swf can only work in flash cs3, but it couldn't work in html page as the chat server can't send the security xml file to this swf, and I have also use Security.loadPolicyFile("http://192.168.139.128/crossdomain.xml"); to load security file, but it took none effect.
    Is there anyone can suggest me ?
    That's very kind of you!

    Hi Franco,
    Yes, I solved that by reinstalling Java 6 Update 21.
    There are three versions for Solaris namely, SPARC, x64 and x86. Our platform is SPARC and I think System admin has installed the wrong version instead of installing SPARC version of Java.
    After installing SPARC version of Java this got resolved. And I confirmed everything is fine by running a small program as below. You can run this program from command line using the -d64 flag. If the installation is wrong you will get the same exception as I mentioned.
    public class Analyzer {
          public static void main(String args[]) throws Exception{
               InputStream fin = new FileInputStream(args[0]);
               int iSize = fin.available();
               byte mvIn[] = new byte[iSize];
               fin.read(mvIn,0,iSize);
               fin.close();
               String strText = new String(mvIn);
               PrintStream fout = new PrintStream(new FileOutputStream(args[0]+".csv"));
               fout.println("Before,After,Seconds");
               Pattern p = Pattern.compile("\\[(?:Full |)GC (\\d*)K->(\\d*)K\\(\\d*K\\), ([\\d.]*) secs\\]");
               Matcher m = p.matcher(strText);
               while(m.find()){
                    fout.println(m.group(1)+ "," + m.group(2) + "," + m.group(3));
               fout.close();
    }Hope this helps.
    Regards,
    Prabhu

  • How to add new fields for ESS leave request

    Hi friends,
    Can u please help me with my issue.......
    My issue is to add new fields in ess/leave request i.e...
    The component needs to be Checked-out through Net Weaver Development Infrastructure, make the necessary enhancements, and finally Check-it-in back to NWDI.
    Custom Function Modules are to be invoked apart from the standard ones that are already available in the Leave Request component – ess~lea inorder to accommodate the extra absence-type logic.
    can u please sujjest me where should i make changes in the given 14 components
    means in which view i have to add these fields.................
    Regards
    Rajesh

    Hi Rajesh ,
    Check whether u are able to find the ess dc's under inactive dc's in webdynpro
    If ur not able to find it then Check the landscape configurator in CMS and also the transport studio and confirm that ess packages are imported fine
    Ganesh ,
               for creating a DTR client u need to open the DTR perspective right click and "create clients" before that go to windows ->preferences of the NWDS and check the development infrastructure URL is gven correctly ...try pinging it once...
    Do check ur SLD is up or not!!!
    Regards
    Krishna
    Message was edited by:
            krishnagopal Mukundan

  • Opinion: new Package for every new custom Component?

    Hi there,
    I am just thinking of some possibilities to structurize my Components I made.
    I wonder if it is useful/good programming to define a new package for each new custom Component?
    So if I define a new MyComponent class extending JFrame should I make a new package:
    "mycomponent"
    containing these subfolders:
    "view"
    "model"
    "controler"
    subfolging "controler" in:
    "listeners"
    "adapters"
    "events"
    Is there any sense to do so? I think this would be the best way to structurize one's components.
    But if you do, you have to include millions of packages if you want to use one of these components :(.
    Please post, what you think.
    Thank you
    Sincerely
    Karlheinz Toni

    nope ;). I would most certainly not want to put every file in a single directory.
    But I like sturctured things. If things belong to each other, it should be visible at once, that they have something to to with each other. And the best method I can figure you is putting them in one package.
    The subpackages should be created, because of the model, that is used for all swing componentd (UI-delegete, MVC...) so that each structural component is where it belongs to.
    I don't like it if tere are 100 events one object could possibly create and you don't know the events from the component (of course you can guess by the name Event :)), but if they are in the same package, you would have to scroll a long way to get the thing you want (either m, v or c).
    So this is why I would do it ;).
    Anyway: do includes make the program run slower (I have read many threads about it, but there are way to many opinions, so I would be grateful if you post your opinions here, thx ;).
    Thanks for your answer,
    Sincerely
    Karlheinz Toni
    p.s.: why wouldn't you put them in a seperate directory (just overkill?), would you use classes that are structured like this if you are looking for a implementation of something and find it in this structure?

  • Safari is not sending proxy-authorization header for some https requests

    Hi,
    I have the problem that sometimes Safari doesnt send the necessary Proxy-Authorization header to our proxy for HTTPS requests.
    The proxy settings are configured in system preferences with a username and password.
    I did packet capture and I can see that most of the time it will work just fine and the trace looks something like this:
    CONNECT communicator.strato.de:443 HTTP/1.0
    Host: communicator.strato.de
    User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; de-de) AppleWebKit/523.12.1 (KHTML, like Gecko) Version/3.0.4 Safari/523.12.2
    Proxy-Authorization: Basic XXXXXXXXXXXXXXXXX== (edited)
    HTTP/1.0 200 Connection established
    While some times it will look something like this :
    CONNECT communicator.strato.de:443 HTTP/1.0
    Host: communicator.strato.de
    User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; de-de) AppleWebKit/523.12.1 (KHTML, like Gecko) Version/3.0.4 Safari/523.12.2
    HTTP/1.0 407 Proxy Authentication Required
    Any idea why Safari sometimes wouldn't send the credentials to the proxy?
    Simon Putz
    Ironport Systems Customer Support

    Hi, I am also facing same problem
    Software : Weblogic jdk1.3.1
    If anyone know the solution ,Please help me
    Thanks,
    Suneel

  • Time Lapse import creates new clip for every frame!

    I shot a time lapse film - five hours reduced to 4 minutes ie one frame every 4 seconds. The iMovie Import wizard created a separate 'Clip' for every frame, (which is unusable), and then crashes the program every time I try to open it, I guess because there are too many 'Clips' to handle.
    Is there a way to import these discontinuous shots as a single clip? If iMovie can't do it, any ideas on a better way? I couldn't get Quicktime Pro to do any better - it opened thousands of separate windows on the desktop.
    Fortunately, the original is on DV, though each frame has a different time stamp on it.
    Thanks for any ideas!

    FYI
    I found that iMovie 6 was able to handle the multiple files and I could export them as an MPEG4 file. iMovie 08 bombed big time.

  • How can I set firefox in order to open a new tab for every new search?

    Every search i've done since the last update, Firefox open the new search in the old tab. I've already fixed the boolean valor in browser.search.openintab to true in about:config, but it's working only with google search (and not, i.e. with youtube search).

    Separate Issue;
    Your System Details shows;
    Installed Plug-ins
    Adobe Shockwave for Director Netscape plug-in, version 12.0.9.149
    Adobe Shockwave for Director Netscape plug-in, version 12.1.3.153
    Having more than one version of a program may cause issues.
    Grab the uninstaller from here:
    '''[http://helpx.adobe.com/flash-player/kb/uninstall-flash-player-windows.html Uninstall Flash Player | Windows]'''
    '''[http://helpx.adobe.com/flash-player/kb/uninstall-flash-player-mac-os.html Uninstall Flash Player | Mac]'''
    Then reinstall the latest version.
    Flash Player '''Version 17.0.0.134<br>https://www.adobe.com/products/flashplayer/distribution3.html'''
    Shockwave Director '''Version 12.1.7.157 http://get.adobe.com/shockwave/'''

  • New ending for every download?

    Is it possible for the Quicktime server to dynamically edit a Quicktime movie and make it available for download? For example, each time the movie is requested, it has a different ending...the difference being a new closing graphic has been appended to the end.
    Thanks.

    http://www.apple.com/quicktime/technologies/interactivity/smil.html
    You would generate the "new" file by using server side includes to alter the text of the .smil file.
    This is very complex to set up but you wouldn't have to create a new .mov file for each instance. Just a database, maybe an Automator "action" for the different image, and a method of uploading those files to your server.

Maybe you are looking for

  • [SOLVED] RT2870 drops connection after pacman update

    Since last pacman upgrade my USB wireless works for just a few seconds while used; while watching transfer speed I see at first full speed and then going slower and slower and in a few secs totally stopped, without being disconnected. I have to reboo

  • IMac, graphics card and Final Cut Studio

    I have an iMac, Intel Core Duo 1.83G, 1 GB 667MHz RAM. I finally made the plunge and bought and tried installing FCStudio 2 but it wants a different graphics card. Can my CPU support FCP and if so, what graphics card is recommended and what sort of R

  • GL PERIOD 화면는 해당 PERIOD 가 존재 BUT OPEN PERIOD 화면에서 볼수 없다.

    제품 : FIN_GL 작성날짜 : 2004-10-14 GL PERIOD 를 PERIOD 화면에서 DEFINE 하였으나 OPEN PERIOD 화면에서 나타나지 않는다. ============================================================== PURPOSE GL PERIOD 를 DEFINE 하고 OPEN하고자 하나 OPEN화면에서 나타나지 않아 찾아보니 GL_PERIOD_STATUS TABLE에 해당 DATA

  • JFileChooser opening with showSaveDialog

    Hello! I have a problem. I want to save a file so I 've created a JFileChooser which opens in the showSaveDialog mode. My problem is how can I have the name of the file predefined so that the user will only choose the directory in which he wants to s

  • Labview programing problem

    Hi, i have problem with my labview programing which in associate with cRio-9025 which also doing the data acquisition of temperature. below is my programing, pls help me to check on it, see error  did i made. Apprecite it, thanks Attachments: asas.pn