query to website

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • eternalLearner
    New Member
    • May 2007
    • 35

    query to website

    i am writing an client application that connects to the server and then sends data to server.
    but, the problem is that i get a java.net.Connec tException: Connection refused error.
    The code i have written is :
    Code:
    //package bdn;
    /*  The java.net package contains the basics needed for network operations. */
    import java.net.*;
    /* The java.io package contains the basics needed for IO operations. */
    import java.io.*;
    /** The SocketClient class is a simple example of a TCP/IP Socket Client.
     *
     */
    
    public class SocketClient {
         public static void main(String[] args) {
            /** Define a host server */
            //find the ip address by ping cmd in unix
            String host = "211.65.63.147";
            /** Define a port */
            int port = 8080;
    
            StringBuffer instr = new StringBuffer();
            String TimeStamp;
            System.out.println("SocketClient initialized");
            
            try {
              /** Obtain an address object of the server */
              InetAddress address = InetAddress.getByName(host);
              /** Establish a socket connetion */
              Socket connection = new Socket(address, port);
              /** Instantiate a BufferedOutputStream object */
              BufferedOutputStream bos = new BufferedOutputStream(connection.
                  getOutputStream());
    
              /** Instantiate an OutputStreamWriter object with the optional character
               * encoding.
               */
              OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
    
            }
            catch (Exception g) {
            System.out.println("Exception: " + g);
                }
    
        }
                
    
    }
    please let me know wat could be the problem.
    Last edited by eternalLearner; Jan 24 '09, 10:17 AM. Reason: sentence formation was incorrect
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Why don't you use a URL and a URLConnection for this purpose?

    kind regards,

    Jos

    Comment

    • eternalLearner
      New Member
      • May 2007
      • 35

      #3
      hmm ok,
      but i wrote this code using url,but even this doesnot work ?
      import java.io.Buffere dReader;
      import java.io.InputSt ream;
      import java.io.InputSt reamReader;
      import java.net.URL;

      public class Sample1 {

      public static void main(String[] args) {

      try {
      //String url =
      // "https://services.nature serve.org/" +
      // "idd/rest/ns/v1.1/globalSpecies/comprehensive";
      String url = "http://www.bioinf.seu. edu.cn/miRNA/index.html";
      String uid = "ELEMENT_GLOBAL .2.100925";
      String nsAccessKeyId = "72ddf45a-c751-44c7-9bca-8db3b4513347";
      String Query = "seqences=/>Example \nCUUGGGAAUGGCA AGGAAACCGUUACCA UUACUGAGUUUAGUA AUGGUAAUGGUUCUC UUGCUAUACCCAGA" ;


      String request = url;
      request = request + "?";
      //request = request + "uid=" + uid;
      //request = request + "&";
      //request = request + "NSAccessKeyId= " + nsAccessKeyId;
      request = request + Query;

      URL serviceURL = new URL(request);
      InputStream is = serviceURL.open Stream();
      //InputStreamRead er isr = new InputStreamRead er(is,"UTF-8");
      InputStreamRead er isr = new InputStreamRead er(is);
      BufferedReader br = new BufferedReader( isr);

      StringBuffer response = new StringBuffer();
      String nextLineFromSer vice = br.readLine();
      while (nextLineFromSe rvice != null) {
      response.append (nextLineFromSe rvice);
      nextLineFromSer vice = br.readLine();
      }

      System.out.prin tln(response);
      }
      catch (Exception e) {
      System.out.prin tln(e);
      }

      }
      }

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        I can't contact that site either (using my browser). Are you sure the url address is correct?

        kind regards,

        Jos

        Comment

        • eternalLearner
          New Member
          • May 2007
          • 35

          #5
          the site is down i guess.
          earlier i was able to connect to the website using browser.
          but ,do u think my program is correct ?

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #6
            Originally posted by eternalLearner
            the site is down i guess.
            earlier i was able to connect to the website using browser.
            but ,do u think my program is correct ?
            Try it with a simple url, e.g. http://www.google.com and see what happens.

            kind regards,

            Jos

            Comment

            • chaarmann
              Recognized Expert Contributor
              • Nov 2007
              • 785

              #7
              enhancement

              Originally posted by eternalLearner
              but ,do u think my program is correct ?
              Yes, it is.
              But you can enhance it. This is what I am using:

              Code:
                 String url = "[URL]http://www.google.com[/URL]";
              StringBuilder response = new StringBuilder(10000);
                 BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
                 String line;
                 while ((line = reader.readLine()) != null) response.append(line);
                 String html = response.toString();
              BufferedReader is faster than StringBuffer. You should use StringBuffer only in multithreaded environment (what you don't have), and if you need to synchronize.

              Also note that if you call "s= new StringBuffer()" or
              "s=new StringBuilder() ", the initial capacity is only 16 characters, so it will need to allocate memory many times to hold an average response of around 7000 bytes in my case. Memory allocation itself is very costly, independent of how many memory you allocate (if it's not some megabytes).
              So just estimate the maximum size of your returned webpage (in my case 10000) and use that for initial capacity.

              Comment

              • JosAH
                Recognized Expert MVP
                • Mar 2007
                • 11453

                #8
                Originally posted by chaarmann
                Memory allocation itself is very costly,
                It isn't; in Java object allocation is no more than a test, an increment of a pointer and the return of the old pointer value. It isn't like a C-like malloc or a C++-like new operator. Garbage collection can be expensive.

                kind regards,

                Jos

                ps. There's also the StringBuilder class that doesn't synchronize on its buffer.

                Comment

                • chaarmann
                  Recognized Expert Contributor
                  • Nov 2007
                  • 785

                  #9
                  Java vs C++ memory allocation

                  Originally posted by JosAH
                  It isn't; in Java object allocation is no more than a test, an increment of a pointer and the return of the old pointer value. It isn't like a C-like malloc or a C++-like new operator. Garbage collection can be expensive.
                  But isn't there a difference between memory allocation and object allocation in Java? I mean to allocate a new object, you can just re-use an old unused object by modifying the pointer (or pointing to a re-usable template if you keep object structure and its data structure separate). But memory allocation goes down deep into the operation system, from chip-cache to first-level cache to second level cache and so on up to saving memory to disk if there is no space available etc. Usually if you need more memory then you need to copy the whole string into a new string. You cannot just increase a pointer and keep the string, because there is usually already some other data allocated at the end of this string. I admit that I don't know how Java handles memory and I know it well from C++. So how should that be possible in Java theoretically? I thought this problem is universal.
                  Also I know that if you allocate small amounts of memory many times, you get memory fragmentation. Then you need to search through the memory map to find a suitable gap. Assuming the average returned html page is 7000 characters long, then you have to find a new gap 9 times:
                  16 --> 32 --> 64 --> 128 --> 256 --> 512 --> 1024 --> 2048 --> 4096 --> 8192
                  Don't you think that's costly?

                  Originally posted by JosAH
                  ps. There's also the StringBuilder class that doesn't synchronize on its buffer.
                  That's what I wanted to express. It's good that you pinpointed this error in my previous post. I wrote: "BufferedRe ader is faster than StringBuffer",
                  but wanted to write: "StringBuilder is faster than StringBuffer". That's why I used it in my program.
                  Quotation from Javadocs, StringBuffer class:
                  "As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread,StringBu ilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization . "

                  Comment

                  • chaarmann
                    Recognized Expert Contributor
                    • Nov 2007
                    • 785

                    #10
                    I read an interesting article about java memory allocation, especially about the generational garbage collector.
                    Quotation: "allocating a new object is nothing more than checking to see if there's enough space left in the heap and bumping a pointer if there is. No searching free lists, best-fit, first-fit, lookaside lists -- just grab the first N bytes out of the heap and you're done."

                    But doesn't that involve copying the old string to the new location every time?

                    Comment

                    • JosAH
                      Recognized Expert MVP
                      • Mar 2007
                      • 11453

                      #11
                      Originally posted by chaarmann
                      But isn't there a difference between memory allocation and object allocation in Java? I mean to allocate a new object, you can just re-use an old unused object by modifying the pointer (or pointing to a re-usable template if you keep object structure and its data structure separate). But memory allocation goes down deep into the operation system, from chip-cache to first-level cache to second level cache and so on up to saving memory to disk if there is no space available etc. Usually if you need more memory then you need to copy the whole string into a new string. You cannot just increase a pointer and keep the string, because there is usually already some other data allocated at the end of this string. I admit that I don't know how Java handles memory and I know it well from C++. So how should that be possible in Java theoretically? I thought this problem is universal.
                      Also I know that if you allocate small amounts of memory many times, you get memory fragmentation. Then you need to search through the memory map to find a suitable gap. Assuming the average returned html page is 7000 characters long, then you have to find a new gap 9 times:
                      16 --> 32 --> 64 --> 128 --> 256 --> 512 --> 1024 --> 2048 --> 4096 --> 8192
                      Don't you think that's costly?
                      That's not how Java memory allocation works; Java keeps a simple heap which is a contiguous chunk of memory; all objects are allocated next to each other until all memory is used; either another chunk of memory is allocated from the OS or the garbage collector is fired up.

                      This scenario makes memory allocation as cheap as can be and all sorts of object pooling etc. merely hinder than help the garbage collector nowadays. (google for "Java garbage collection" and you'll find the discussions).

                      The garbage collector applies a "generation scavenging" strategy, i.e. lots of objects in Java just live for a short while (e.g. local objects) and only some of them survive the first (small) collection phases. They are copied to an 'eden' space where they won't be affected by those small garbage collection phases. Only when all else fails (maximum heap size has been reached and no more memory could be collected) a full garbage collection is started that also checks the 'eden' space.

                      C and C++ use a much more naive approach and they don't move the allocated chunks of memory around so they have to maintain some form of a linked list of free/allocated memory. That can cause fragmentation but Java doesn't suffer from it.

                      Several containers (StringBuilder, ArrayList etc.) anticipate on the allocation of more memory by allocating (a bit) more memory than is strictly needed so they can use that memory in the near future. Strings don't do that, they're immutable and catenating Strings over and over again is a very inefficient operation.

                      As a rule of thumb: don't try to help the garbage collector; it knows how to do its job. Memory allocation is as fast as can be; constructors simply initialize/modify this already allocated memory.

                      kind regards,

                      Jos

                      Comment

                      • chaarmann
                        Recognized Expert Contributor
                        • Nov 2007
                        • 785

                        #12
                        And the String data itself? Isn't it copied over to the new memory location every time? Or does String use an internal array of allocated memory chunks, so that a string must not be linear in memory?

                        Jos, so what do you think in this case, how much times is it faster? On a scale from "not measurable percentage" to "many times"?
                        (If I write "new StringBuilder(1 0000)" instead of "new StringBuilder() " for an total average of 7000 characters loaded which are added line by line ?)

                        Comment

                        • JosAH
                          Recognized Expert MVP
                          • Mar 2007
                          • 11453

                          #13
                          Originally posted by chaarmann
                          And the String data itself? Isn't it copied over to the new memory location every time? Or does String use an internal array of allocated memory chunks, so that a string must not be linear in memory?
                          Most of the time the char buffers are copied over. An exception to the rule is the substring() method; the newly created String shares the buffer with the original String. If you read the source code of that class (see the src.zip file in your JDK installation) you'll see that the String class plays a few tricks with the StringBuffer class as well ...

                          Originally posted by chaarmann
                          Jos, so what do you think in this case, how much times is it faster? On a scale from "not measurable percentage" to "many times"?
                          (If I write "new StringBuilder(1 0000)" instead of "new StringBuilder() " for an total average of 7000 characters loaded which are added line by line ?)
                          Of course preallocating a large enough buffer will be faster than simply incrementing the buffer over and over again; you don't have to copy the data in the buffer over and over again. otoh, 7000 characters isn't that much ...

                          kind regards,

                          Jos

                          Comment

                          • eternalLearner
                            New Member
                            • May 2007
                            • 35

                            #14
                            hi, thanks for all the inputs
                            I did as suggested, but the code still doesnot work.
                            Am I posting the query in incorrect format ??
                            the site is up now,
                            Last edited by eternalLearner; Feb 28 '09, 08:11 AM. Reason: incorrect sentence formation

                            Comment

                            Working...