2015-09-29 85 views
0

我想用套接字读写byte[]数据,但无法停止数据流。如何停止DataInputStream get byte []?

这是我的服务器:

public class Server { 
    public static void main(String[] args) throws IOException { 
     System.out.println("Welcome to Server side"); 
     DataInputStream in; 
     DataOutputStream out; 

     ServerSocket servers = null; 
     Socket fromclient = null; 

     // create server socket 
     try { 
      servers = new ServerSocket(4444); 
     } catch (IOException e) { 
      System.out.println("Couldn't listen to port 4444"); 
      System.exit(-1); 
     } 

     try { 
      System.out.print("Waiting for a client..."); 
      fromclient = servers.accept(); 
      System.out.println("Client connected"); 
     } catch (IOException e) { 
      System.out.println("Can't accept"); 
      System.exit(-1); 
     } 

     in = new DataInputStream(fromclient.getInputStream()); 
     out = new DataOutputStream(fromclient.getOutputStream()); 
     String input = "", output; 

     System.out.println("Wait for messages"); 

     byte[] bytes = new byte[16*1024]; 

     int count; 
     while ((count = in.read(bytes)) > 0) { 
      byte[] mass = "some data".getBytes("UTF-8"); 
      out.write(mass, 0, count); 
      System.out.println(Arrays.toString(bytes)); 
     } 

     out.close(); 
     in.close(); 
     fromclient.close(); 
     servers.close(); 
    } 
} 

当我从客户端接收数据,它会打开一个无限流不停止。

我该如何阻止这个DataInputStream

+0

“我无法停止流”不是一个问题描述。再试一次。 NB'System.out.println(Arrays.toString(bytes));'应该是'System.out.println(Arrays.toString(bytes,0,count));', – EJP

+0

“System.out.println(Arrays。 toString(bytes,0,count));“显示错误参数 – Pavel

回答

1

关闭客户端(或服务器端)的连接。只要连接处于打开状态,服务器就会等待发送数据。

在适当的设置中,您将拥有一个定义良好的协议,然后可以包含关闭消息以在客户端决定断开连接时通知服务器。简单地关闭连接是实现这一目标的“原始”方式,但不是很优雅。