简体   繁体   中英

java reading from Socket hangs

I have to implement a communication between terminal and a POS terminal over TCP/IP. What I have is IP and port of pos terminal and protocol specification.

In java I have done a simple example to write to a socket, but my app freeze when I want to read from a socket (until timeout is reached)..

What I'am doing wrong?

 try {
        pos = new Socket("172.16.201.217", 1500);
        pos.setSoTimeout(5000);

        output = new DataOutputStream(pos.getOutputStream());

        System.out.println("is connected?:" + pos.isConnected());
        String amount = "100";
        String p = "000000123401100" + FS + amount + FS + FS + "+0" + FS + "705" + FS + FS + FS + FS + FS + FS + FS + ETX;

        //Podatki is a method which adds some additional chars + CRC.. 
        byte[] protokol = Podatki(p);

        //here I send a complete array of bytes to my pos...
        output.write(protokol, 0, protokol.length);
        output.flush();

        Thread.sleep(1000);


        input = new BufferedReader(new InputStreamReader(pos.getInputStream()));
        String line = "";
        String response = "";
        while ((line = input.readLine()) != null) {
            System.out.println(line);
            response = response + line + "\n";
            if (input.ready() == false) {
                break;
            }

what I get is timeout exception.. What I expect is a response from pos terminal which can be ACK (acknowledge) or NAK (negative acknowledge).

thank you.

It is possible that your message is not finished (may be it is waiting for a particular end of message character or sequence of characters for example) so the POS is waiting for the rest of the message. In this situation the timeout on your code comes before an error message of pos.

To check it use a socket sniffer between your code and the POS so you can see what exactly is passing between client and server and viceversa.

You seem to be reading lines but not writing lines. readLine() will block until end of stream or an exception or a line terminator is encountered. If you don't send a line terminator and don't close the socket and no network errors occur, readLine() at the peer will block forever.

Send a line terminator: \\n or \\r\\n .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM