本帖最后由 sysmaid 于 2013-06-04 15:18:37 编辑

解决方案 »

  1.   

    字迹先顶一下。
    报错是在第二个while中,这一句:
    while((len = input.read(header, 0, 2)) != -1){
    我让他每次读两个字节,就是想看看读到的和报文头写的长度是否一致。
    但为何读到最后,没有结束循环,而是一直等到了time out呢?
      

  2.   

    你这个input的流在第一个while循环里面已经读到末尾了,所以返回-1后退出第一个循环。
    而你的第二个while循环任然再去使用input读取数据,这个时候的input流里面肯定没有东西让你再继续读下去了,又因为input.read()是个阻塞的方法,会一直等待下一个字节的出现,从而导致timeout。
        /**
         * Reads some number of bytes from the input stream and stores them into
         * the buffer array <code>b</code>. The number of bytes actually read is
         * returned as an integer.  This method blocks until input data is
         * available, end of file is detected, or an exception is thrown.
         *
         * <p> If the length of <code>b</code> is zero, then no bytes are read and
         * <code>0</code> is returned; otherwise, there is an attempt to read at
         * least one byte. If no byte is available because the stream is at the
         * end of the file, the value <code>-1</code> is returned; otherwise, at
         * least one byte is read and stored into
     <code>b</code>.
         *
      

  3.   

    我觉得不是这样的,我一次只读了2个字节,而且总长度是60,第二个while里也读了29次,然后应该结束的,但他没有,一直到报time out退出。
    我在想是不是因为socket是保持连接的,所以read方法没有退出,一直等到time out才退出。
      

  4.   

    我觉得不是这样的,我一次只读了2个字节,而且总长度是60,第二个while里也读了29次,然后应该结束的,但他没有,一直到报time out退出。
    我在想是不是因为socket是保持连接的,所以read方法没有退出,一直等到time out才退出。额,我刚看错了,你的第一个while循环只读取了2个字节,就break掉了,我囧啊。第二个循环读取58个字节,打印出结果都是对的。之所以没有退出,的确是因为你的socket是保持连接的,这个是正常的,因为你的连接不是只发送一次数据就断开了,而是保持一个长连接,服务器等待你的client发送下一次的消息。你如果想要让input.read()返回-1而退出的话,需要你的client端关闭连接,即socket.close()后,就是正常退出了。
      

  5.   

    即client的socket.close后,才会发送给server端结尾符,从而才会read到结尾信息而返回-1