wood burning stoves 2.0*
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
Author

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();
chatarea.add(msg_fromserver);
}
}
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
response)
//[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 (event.id) {
case Event.ACTION_EVENT:
if (event.target == input || event.target == 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 ]
regards,
ch.praveen
 
wood burning stoves
 
subject: Multiple URLConnections