java - Add timeout in receiving message - socket -
i have method sending message on socket , receiving answer. how put timer, if there no answer example 1 sec put information timeout ?
public boolean sendforcemessage(final forcemessagetcp message) { boolean result = true; system.out.println("******************sendforcemessage**********************************"); new thread() { public void run() { try { system.out.println("ipaddress="+ipaddress); system.out.println("port="+port); system.out.println("is reachable="+ping()); for(int i=0;i<message.tobytes().length;i++) system.out.println("fragment["+i+"]="+message.tobytes()[i]); socket = new socket(ipaddress, port); outputstream socketoutputstream = (outputstream) socket .getoutputstream(); socketoutputstream.write(message.tobytes()); inputstream socketinputstream=(inputstream)socket.getinputstream(); byte[] buffer=new byte[256]; int numberreceived=socketinputstream.read(buffer); if(numberreceived!=-1) new fdresponsemessage(buffer); socket.close(); } catch (unknownhostexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } }.start(); return result; }
http://www.javacoffeebreak.com/articles/network_timeouts/
happy reading
edit
forgot socket options, please check out: http://download.oracle.com/javase/1.4.2/docs/api/java/net/socket.html#setsotimeout(int)
basically set so, therefor call read() block amount of time specify
Comments
Post a Comment