By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,018 Members | 894 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,018 IT Pros & Developers. It's quick & easy.

query to website

P: 35
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.ConnectException: Connection refused error.
The code i have written is :
Expand|Select|Wrap|Line Numbers
  1. //package bdn;
  2. /*  The java.net package contains the basics needed for network operations. */
  3. import java.net.*;
  4. /* The java.io package contains the basics needed for IO operations. */
  5. import java.io.*;
  6. /** The SocketClient class is a simple example of a TCP/IP Socket Client.
  7.  *
  8.  */
  9.  
  10. public class SocketClient {
  11.      public static void main(String[] args) {
  12.         /** Define a host server */
  13.         //find the ip address by ping cmd in unix
  14.         String host = "211.65.63.147";
  15.         /** Define a port */
  16.         int port = 8080;
  17.  
  18.         StringBuffer instr = new StringBuffer();
  19.         String TimeStamp;
  20.         System.out.println("SocketClient initialized");
  21.  
  22.         try {
  23.           /** Obtain an address object of the server */
  24.           InetAddress address = InetAddress.getByName(host);
  25.           /** Establish a socket connetion */
  26.           Socket connection = new Socket(address, port);
  27.           /** Instantiate a BufferedOutputStream object */
  28.           BufferedOutputStream bos = new BufferedOutputStream(connection.
  29.               getOutputStream());
  30.  
  31.           /** Instantiate an OutputStreamWriter object with the optional character
  32.            * encoding.
  33.            */
  34.           OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
  35.  
  36.         }
  37.         catch (Exception g) {
  38.         System.out.println("Exception: " + g);
  39.             }
  40.  
  41.     }
  42.  
  43.  
  44. }
  45.  
please let me know wat could be the problem.
Jan 24 '09 #1
Share this Question
Share on Google+
13 Replies


Expert 10K+
P: 11,448
Why don't you use a URL and a URLConnection for this purpose?

kind regards,

Jos
Jan 24 '09 #2

P: 35
hmm ok,
but i wrote this code using url,but even this doesnot work ?
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class Sample1 {

public static void main(String[] args) {

try {
//String url =
// "https://services.natureserve.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 \nCUUGGGAAUGGCAAGGAAACCGUUACCAUUACUGAGUUUAGUAAUGGU AAUGGUUCUCUUGCUAUACCCAGA";


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.openStream();
//InputStreamReader isr = new InputStreamReader(is,"UTF-8");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

StringBuffer response = new StringBuffer();
String nextLineFromService = br.readLine();
while (nextLineFromService != null) {
response.append(nextLineFromService);
nextLineFromService = br.readLine();
}

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

}
}
Jan 27 '09 #3

Expert 10K+
P: 11,448
I can't contact that site either (using my browser). Are you sure the url address is correct?

kind regards,

Jos
Jan 28 '09 #4

P: 35
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 ?
Jan 28 '09 #5

Expert 10K+
P: 11,448
@eternalLearner
Try it with a simple url, e.g. http://www.google.com and see what happens.

kind regards,

Jos
Jan 28 '09 #6

Expert 100+
P: 785
@eternalLearner
Yes, it is.
But you can enhance it. This is what I am using:

Expand|Select|Wrap|Line Numbers
  1.    String url = "http://www.google.com";
  2. StringBuilder response = new StringBuilder(10000);
  3.    BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
  4.    String line;
  5.    while ((line = reader.readLine()) != null) response.append(line);
  6.    String html = response.toString();
  7.  
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.
Jan 29 '09 #7

Expert 10K+
P: 11,448
@chaarmann
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.
Jan 29 '09 #8

Expert 100+
P: 785
@JosAH
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?

@JosAH
That's what I wanted to express. It's good that you pinpointed this error in my previous post. I wrote: "BufferedReader 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,StringBuilder. 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. "
Jan 29 '09 #9

Expert 100+
P: 785
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?
Jan 29 '09 #10

Expert 10K+
P: 11,448
@chaarmann
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
Jan 29 '09 #11

Expert 100+
P: 785
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(10000)" instead of "new StringBuilder()" for an total average of 7000 characters loaded which are added line by line ?)
Jan 29 '09 #12

Expert 10K+
P: 11,448
@chaarmann
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 ...

@chaarmann
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
Jan 29 '09 #13

P: 35
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,
Feb 28 '09 #14

Post your reply

Sign in to post your reply or Sign up for a free account.