Set timeout on receiving data

I have a function to send data on the Socket class in Java. When I send data, I need to get some data. The problem is how to set a timeout for waiting for data for 2 seconds (if I do not receive data in 2 seconds, I need to understand what a communication error message is and showing a message). This is my code, any help?

    public boolean SendMonitorMessage(
            final MonitorRequestRepeatMessageTCP message) {
        boolean result = true;
        System.out
                .println("****************** SEND MONITOR REQUEST REPEAT MESSAGE TCP **********************************");

        // new Thread() {
        // public void run() {
        int prevService=message.GetService();
        synchronized (socket) {
            try {
                System.out.println("IPADDRESS=" + ipAddress);
                System.out.println("PORT=" + port);
                System.out.println("Is reachable=" + Ping());
                message.PrintMessage(message.toBytes());

                OutputStream socketOutputStream = (OutputStream) socket
                        .getOutputStream();
                socketOutputStream.write(message.toBytes());

                InputStream socketInputStream = (InputStream) socket
                        .getInputStream();

                byte[] buffer = new byte[256];
                List<byte[]> received = new LinkedList<byte[]>();
                int numberReceived;
                byte[] tempBuffer;

                while ((numberReceived = socketInputStream.read(buffer)) != -1) {
                    tempBuffer = new byte[numberReceived];
                    ByteBuffer baferce = ByteBuffer.wrap(tempBuffer);
                    baferce.put(buffer, 0, numberReceived);
                    received.add(tempBuffer);
                }

                if (received.size()>0){
                    new MonitorResponseMessageTCP(received, message.GetMonitorVariablesArrayList(), prevService);
                }
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return true;
    }
+3
source share
1 answer

Socket ServerSocket. setSoTimeout, . , SocketTimeoutException, , , .

setSoTimeout , -.

while ((numberReceived = socketInputStream.read(buffer)) != -1) {

socket.setSoTimeout(2000);

catch(SocketTimeoutException) try/catch, .

+6

Source: https://habr.com/ru/post/1791994/


All Articles