aspose file tools
The moose likes Sockets and Internet Protocols and the fly likes reading and writing socket problem Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Reply Bookmark "reading and writing socket problem" Watch "reading and writing socket problem" New topic
Author

reading and writing socket problem

Natalia Lopez
Ranch Hand

Joined: Feb 17, 2005
Posts: 41
Hi!
I need to send a text to a socket and I should receive the responde in no more than 20 second. The following code send the text ok over the socket but delay sometimes 35 second receiving the response.
It seems that not check the socket all the time and the response arrived too late.
How can I read more quick from the socket?

Here the code


try
{
socket = new Socket(hostname,port);
System.out.println("Connected!!");


String request = "Hola";


InputStream in = socket.getInputStream ();
OutputStream out = socket.getOutputStream();

writeToSocket(socket,request, out);

StringBuffer response = new StringBuffer();

byte[] b = new byte[4096];

for (int n; (n = in.read(b)) != -1 {
response.append(new String(b, 0, n));
}


System.out.println("RESPONSE: "+response.toString());


in.close();
out.close();
socket.close();

}
catch (IOException e)
{


e.printStackTrace();
}


Some body can give me and idea Thanks a lot!
Natalia
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Your read will block until some bytes become available over the socket. There might be delays caused by the network or the sending partner being slow.

I had a nasty setup like this at work where the partner gets into a state that NEVER responds, so my read could hang forever. I moved the socket communication onto its own thread so the main thread could give up after a while and go on with life.

Any of that sound like your situation?


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Natalia Lopez
Ranch Hand

Joined: Feb 17, 2005
Posts: 41
Yes it is true, the code can be waiting forever. How did you do de main tread to consider a time out? and where did you set the time out?

Naty
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I posted a bit of the logic in this thread on threads. See if that would work for you. That doesn't kill the blocked thread - it goes on blocking and eventually finishes but I don't wait for it.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: reading and writing socket problem
 
Similar Threads
sending mail using servlet
socket "connection reset"
PC Connected to Internet and Internet Connectivity?
creating concurrent server using separate threads??
Problem with Image and .zip file(Uploading)