File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Multiple URLConnections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Multiple URLConnections" Watch "Multiple URLConnections" New topic

Multiple URLConnections

ch praveen
Ranch Hand

Joined: Mar 08, 2004
Posts: 67
Hello Friends,
In my application on the client side (applet), there is need to keep in touch with the servlet continuosly. For this purpose I have created a thread which accomplishes the above goal as follows:
public void run() {
while (true) {
String msg_fromserver = getNextMessage();
String getNextMessage() {
String nextMessage = null;
while (nextMessage == null) {
try {
URL url = new URL(getCodeBase(), "/examples/servlet/ChatServlet");
//NOTE:: As Iam using O'Reilly utility, 'HttpMessage' to establish
//connection with the servlet. I have excluded that code to avoid
//unnecessary complexity and confusion. Below lines reflect
//the basic alogithm to establish the connection with the servlet.

//[1]Establish a URLConnection.
//[2]Write data to servlet through its URLConnection's output stream.
//[3]Get Input Stream from URLConnection and read object(servlet's
//[4]Update nextMessage, variable's value from the object we
//obtained from the URLConnection's Input Stream.
catch (Exception e) {
System.out.println("Exception: " + e);
return nextMessage + "\n";
The above Thread will be running continuosly and posts some query to the servlet for which it sends relevant object in response.
Now, when user clicks some button, I have to establish a connection with the servlet and must post a message to it, which is as follows:
public boolean handleEvent(Event event) {
switch ( {
case Event.ACTION_EVENT:
if ( == input || == sendbutton) {
try {
URL url = new URL(getCodeBase(), "/examples/servlet/ChatServlet");
// Establish a URLConnection and write message to the server
// through the URLConnection's output stream.
catch (Exception e) {
System.out.println("Exception:: " + e);

The above code is some times fetching IOException. My question is , "can't we use multiple URLConnections from an applet to establish connection with a same servlet or different servlets simultaneously" [ In the above program one loop is constantly establishing a connection with servlet and getting responses and also when an appropriate event occurs, it also try to establish a connection with the servlet and post a message to the servlet which may lead to concurrency ]
I agree. Here's the link:
subject: Multiple URLConnections
It's not a secret anymore!