Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

reading and writing socket problem  RSS feed

 
Natalia Lopez
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Natalia Lopez
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!