473,386 Members | 1,705 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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.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
13 2993
JosAH
11,448 Expert 8TB
Why don't you use a URL and a URLConnection for this purpose?

kind regards,

Jos
Jan 24 '09 #2
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
JosAH
11,448 Expert 8TB
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
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
JosAH
11,448 Expert 8TB
@eternalLearner
Try it with a simple url, e.g. http://www.google.com and see what happens.

kind regards,

Jos
Jan 28 '09 #6
chaarmann
785 Expert 512MB
@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
JosAH
11,448 Expert 8TB
@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
chaarmann
785 Expert 512MB
@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
chaarmann
785 Expert 512MB
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
JosAH
11,448 Expert 8TB
@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
chaarmann
785 Expert 512MB
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
JosAH
11,448 Expert 8TB
@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
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

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

Similar topics

4
by: leegold2 | last post by:
Let's I do a mysql query and then I do a, for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {...} and it gives me this: PageID Title URL Description 1 lee's ...
14
by: Bruce W...1 | last post by:
I do a query to MySQL using PHP. Well actually I do too many of them which is the problem, it's too slow. I think maybe an inner join or something would be better but I can't figure this out. ...
1
by: Lukelrc | last post by:
Hi. I have a table (websitehits) which holds statistics about websites. This table has a date field (datecounted). What I need is to create a query which returns a list of dates between two date...
2
by: tdmailbox | last post by:
I have a database with three tables tbl_listings - listings of houses on for sale tbl_intersted - table which tracks if a user is interested in the listing, it has two columns mls(the key for...
3
by: MX1 | last post by:
Here's a type of query I'm always having trouble with. There are 4 fields in a web access log table. User | Date | Time | Destination I want to show all the instances of a user hitting a...
4
by: Wim Verhavert | last post by:
Hi all, For gathering certain information in building my database, I'm depending on the things I found on the web, especially one website (let's call it www.mywebsite.com). Is there a way to...
9
by: Jeff Gardner | last post by:
Greetings: I have an UPDATE query (php 5.1.6/mysql 5.0.24a on apache 2.2) that appears to execute with no errors (php,mysql, or apache) but the data in the "UPDATED" table doesn't change. I've...
9
by: JJM0926 | last post by:
I'm trying to create a running totals query in access 97. I have followed the directions on how to do it from Microsofts website article id 138911. I took their code they had and replaced it with...
8
siridyal
by: siridyal | last post by:
I have a wholesale website that i'm working on that shows hundreds of items that are updated from time to time. These items are kept in a mysql database with several tables. I want to let the...
3
by: DigitalWallfare | last post by:
Hi all, This is my first post here, but i've lurked for a while. I'm working on a website but have come across a major stumbling block in the code: I've managed to structure the search query...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.