简体   繁体   English

从套接字读取Java挂起

[英]java reading from Socket hangs

I have to implement a communication between terminal and a POS terminal over TCP/IP. 我必须通过TCP / IP实现终端和POS终端之间的通信。 What I have is IP and port of pos terminal and protocol specification. 我所拥有的是pos终端的IP和端口以及协议规范。

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).. 在Java中,我做了一个简单的示例来写入套接字,但是当我想从套接字读取消息时(直到达到超时),我的应用程序冻结了。

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). 我得到的是超时异常。我期望的是来自pos终端的响应,可以是ACK(确认)或NAK(负确认)。

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. 您的消息可能未完成 (例如,它正在等待消息字符的特定结尾或字符序列),因此POS正在等待消息的其余部分。 In this situation the timeout on your code comes before an error message of pos. 在这种情况下,代码上的超时将在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. 要检查它,请在代码和POS之间使用套接字嗅探器,以便您可以看到客户端和服务器之间到底传递了什么,反之亦然。

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. readLine()将阻塞,直到流结束或遇到异常或行终止符。 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. 如果您不发送线路终止器并且不关闭套接字并且没有发生网络错误,则对等方的readLine()将永远阻塞。

Send a line terminator: \\n or \\r\\n . 发送行终止符: \\n\\r\\n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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