开发者

Add timeout in receiving message - socket

开发者 https://www.devze.com 2023-02-08 18:45 出处:网络
I have method for sending message over socket and receiving answer. How to put timer, if there is no answer for example 1 sec to put information timeout ?

I have method for sending message over socket and receiving answer. How to put timer, if there is no answer for example 1 sec to 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());

                InputStrea开发者_如何学Pythonm 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 about socket options, please check this out: http://download.oracle.com/javase/1.4.2/docs/api/java/net/Socket.html#setSoTimeout(int)

Basically you set a SO, therefor your call to read() will only block for the amount of time you specify

0

精彩评论

暂无评论...
验证码 换一张
取 消