繁体   English   中英

无法从Java TCP套接字中的输入流读取数据字节

[英]Unable to read data bytes from input stream in java tcp socket

在我的服务器代码中,我向客户端发送了不同的请求并返回响应,但是仅访问了第一个读取请求,在访问第二个读取语句期间,它无法读取数据字节,我的代码如下。

private static boolean Rt_Request(int id,Object client)throws Exception  
{ 

int size=5; 

byte[] buf=new byte[size];

char[] cbuf=new char[32]; 

int byteRead; Socket s=(Socket)client;


BufferedReader in1= new BufferedReader(new InputStreamReader(s.getInputStream()));

PrintStream out=new PrintStream(s.getOutputStream());

try {
    buf[0]=0x02;            
    buf[1]=0x09;            
    buf[2]=0x01;            
    buf[3]=0x00;            
    buf[4]=0x03;
    Thread.sleep(5000);

    out.write(buf, 0, 5);      
} catch(Exception e) {        
     System.out.println("Error Occured...."+e);                             
}

byteRead=0;

while(byteRead!=1) {
        try {

            byteRead=in1.read(cbuf, 0, 1);// Have problem on this line,here I am unable to read data bytes.
            for(int i=0;i<byteRead;i++)
            {
            System.out.println(cbuf[i]);
            }
            if(byteRead==0)
            {
                System.out.println("Breaking.....");
                return false;
            }         
        }
        catch(Exception e) {
            System.out.println("Error Occured...."+e);
            return false;
        }

    }       
        return true;   
    } catch(Exception e) {
        System.out.println("System is not Connected..."+e);
        return false;
    }

几乎尝试过所有未关闭的套接字,read.available();, read.fully(); 等。无法获得解决方案。我已经在TimerTask类的run方法中编写了此函数。 任何帮助将不胜感激

javadocs说BufferedReader#read(char [],int,int)返回:读取的字符数;如果已到达流的末尾,则返回-1

因为你做

byteRead=in1.read(cbuf, 0, 1);

while(byteRead!=1)

更改为

while(byteRead != -1)
byteRead=in1.read(cbuf, 0, 1);

该行仅读入一个值,并且由于您在进入for循环之前不会再次调用它,因此应该在标准输出中获得读取值的1 println。

如果没有可用数据,则底层InputStreamread方法将阻塞(即挂起/等待)。

该方法将阻塞,直到输入数据可用,检测到文件结尾或引发异常为止。

我强烈怀疑是这种情况。 您可以通过在阅读器上调用in1.ready()进行检查。

刷新输出缓冲区

out.flush();

写入字节后,否则它们可能会在本地缓冲。

read()阻塞,直到至少有一个字节可用为止。 也许您没有发送它,或者没有正确刷新它,或者您可能在同一套接字上创建了多个BufferedReaders

NB bytesRead read(cbuf, 0, 1).成功read(cbuf, 0, 1).后永远不能为零read(cbuf, 0, 1).

暂无
暂无

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

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