1

My client first creates a url object with the url of the server (containing the servlet) and sends data to the servlet using the following code:

URL url = new URL("http://localhost:8080/hello");
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    ObjectOutputStream out=new ObjectOutputStream(connection.getOutputStream());
    out.writeObject(stringToReverse);

After receiving the required data from the server, the client again needs to send a data to the servlet. Should I close the above ObjectOutptStream and create a new one within the same connection to send the data? How should it be done?

Another question that I have is that each time I write data into the outputstream of the client, should I create a separate ObjectInputStream in the servlet?

jmort253
  • 32,054
  • 10
  • 92
  • 114
Ashwin
  • 10,386
  • 29
  • 103
  • 172
  • This is abuse of the HTTP protocol. Read this for the proper usage: http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests – BalusC Jan 25 '12 at 13:35

1 Answers1

1

Since these are all specific to a connection that ends as soon as the data is sent, I would suggest just instantiating them each time you make a connection. These objects are initialized using constructors instead of setter methods, and this suggests that the classes were not intended to be reused over and over again..

jmort253
  • 32,054
  • 10
  • 92
  • 114
  • should i create a new objectoutputstream each time i wat to send data and on the other side create a new corresponding objectinputstream? – Ashwin Jan 25 '12 at 08:23
  • That's what I would do. It seems like a lot of unnecessary overhead to try to keep those objects alive between requests. If you have time and really want to experiment, try it both ways and put in some timing code. I'm sure the difference is negligible. :) – jmort253 Jan 25 '12 at 08:30