Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout on a java util scanner?

I have the following problem, I have a simple TCP class in my application that sends a message off to a device for a query, the device then responds with the message however there is no end of line character of any description because it is coming from a serial converter, after initially atempting to use the readline function and discovering it requires the eol character before outputting I have tried the scanner function which works fine unless the device doesnt reply to that request for some reason, my application then freezes, is it possible to set a timeout on the scanner function so that it then drops the connection and moves on or is there a better way to do this? my code is below:

public String Send_TCP ( InetAddress IPAddress, int POrt, String InData) throws IOException
         {      

        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            socket = new Socket(IPAddress, POrt);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection");
            System.exit(1);
        }

        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        ;

        System.out.print("Connected, Sending:"+ InData);

        out.println(InData);
        System.out.println("Equals");
        String str1 = new Scanner(in).useDelimiter(">").next() + ">";
        System.out.println(str1);
        System.out.println("Equals");
        out.close();
        in.close();
        read.close();
        socket.close();
        return str1;
    }
}
like image 547
James Avatar asked Jan 20 '26 14:01

James


1 Answers

I'm not sure that I understand your question correctly but you can set a timeout on the socket: socket.setSoTimeout(int timeout). See: javadoc

like image 159
Nathanael Avatar answered Jan 22 '26 08:01

Nathanael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!