2017-06-17 40 views
-1

OutputStream的收盘前收到的消息我在服务器的InputStream为什么不能在TCP

DataInputStream in=new DataInputStream(c1.getInputStream()) ; System.out.println(in.readUTF());

它的工作原理使用这样的代码在我的客户

DataOutputStream out = new DataOutputStream(client.getOutputStream()); 
    out.writeUTF(mssage); 
    out.flush(); 

    while(true){ 

    } 

与此代码。 但是,如果我用这个下面的代码在我的客户

OutputStream out=client.getOutputStream(); 

    out.write(mssage.getBytes()); 


    out.flush(); 

    while(true){ 

    } 

这个代码在我的服务器

InputStream in= c1.getInputStream(); 
     byte [] b=new byte [32]; 

     while((in.read(b))!=-1){ 

      toprint+=new String (b); 

     } 
     System.out.print(toprint); 

,直到我关闭客户端或关闭的OutputStream,服务器无法接收按摩会出现连接重置错误。 是什么原因?

回答

0

您的服务器正在读取其输入流,直到流的结束才打印任何内容,并且只有当对等关闭套接字或关闭套接字以输出时,套接字上的流结束才会发生。

另一个问题是您的读取循环不正确,因为它忽略了读取计数。

试试这个:

int count; 
while ((count = in.read(b)) != -1){ 

    toprint+=new String (b, 0, count); 
    System.out.write(b, 0, count); 
} 
+0

但它为什么不关闭套接字或DataOuputStream,当我使用DataOuputStream在我的客户端发送和使用DataInputStream类在我的服务器来读取。 –

+0

我无法制作头部或尾部,但它与'DataInput/OutputStream'无关。这是所有套接字流的行为方式。您正在读取数据流结束,数据流结束意味着对等方已断开连接。尝试在收到字符时打印这些字符。 – EJP