2011-06-13 7 views
7

Tengo un hilo que lee caracteres desde un lector de búfer (creado a partir de una toma de la siguiente manera):Java - Lectura de un lector tamponada (a partir de una toma de corriente) está en pausa el hilo

inputStream = new BufferedReader(new InputStreamReader(clientSock.getInputStream())); 

Este código sólo funciona una vez. Por ejemplo, si un cliente se conecta y envía esto: "Esto es una prueba" y "Esta es otra prueba", la salida de host es:

Reading from stream: 
Chars read from stream: 16 
This is a test 

Reading from stream: 

Tenga en cuenta que el programa no recibe "Esta es otra prueba ", porque está atascado en la lectura de la secuencia. ¿Hay alguna forma de lidiar con esto sin reducir el tamaño del búfer? Este es el código de la rosca:

public void run() { 
     boolean dataRecieved = false; 
     char[] inputChars = new char[1024]; 
     int charsRead = 0; 

     while (!stopNow) { 

      try { 
       Thread.sleep(getDataDelay); 

       //Read 1024 characters. Note: This will pause the thread when stream is empty. 
       System.out.println("Reading from stream:"); 
       charsRead = inputStream.read(inputChars); //<< THIS LINE IS PAUSING THE THREAD!> 


       if ((charsRead = inputStream.read(inputChars)) != -1) 
       { 
        System.out.println("Chars read from stream: " + charsRead); 
        System.out.println(inputChars); 
        System.out.flush(); 
       } 


      } catch (IOException e) { 
       System.out.println("IOException"); 
       //TODO: CLIENT HAS DISCONNECTED... 
      } catch (InterruptedException e) { 
       System.out.println("Interrupted"); 
       // Sleep was interrupted. 
      } 

     } 

    } 

Código de cliente/remitente (no es mi código):

public static void main(String[] args) throws IOException { 
     // <<<<<<<<<<<CLIENT>>>>>>>>>>>>>>> 

     Socket sock = new Socket("127.0.0.1", 3000); 
     // reading from keyboard (keyRead object) 
     BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in)); 
     // sending to client (pwrite object) 
     OutputStream ostream = sock.getOutputStream(); 
     PrintWriter pwrite = new PrintWriter(ostream, true); 

     // receiving from server (receiveRead object) 
     InputStream istream = sock.getInputStream(); 
     BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream)); 

     System.out.println("Start the chitchat, type and press Enter key"); 

     String receiveMessage, sendMessage;    
     while(true) 
     { 
      sendMessage = keyRead.readLine();  // keyboard reading 
      pwrite.println(sendMessage);  // sending to server 
      System.out.flush();   // flush the data 

      if((receiveMessage = receiveRead.readLine()) != null) //receive from server 
      { 
       System.out.println(receiveMessage); // displaying at DOS prompt 
      }   
     }    
    }   
+0

Asegúrese de que el otro envía algo. – khachik

+0

http://stackoverflow.com/questions/6293049/java-networking/6293184#6293184 –

+0

Ese enlace no me ayuda. Ya estoy usando hilos. El problema es que no puedo recibir datos del cliente más de una vez. – David

Respuesta

9

java.io.InputStream.read() es una llamada bloqueo, lo que significa que si no hay datos disponibles de la el hilo se detiene hasta que los datos estén disponibles.

Para las E/S sin bloqueo, use las clases del paquete java.nio.

2

Su "remitente" está esperando recibir datos del "receptor", y aquí es donde el código espera indefinidamente. ¿Se supone que el receptor está enviando una respuesta cuando recibe un mensaje?

-1

Tienes que crear ServerSocket que escuchen al cliente en cada ciclo.

ServerSocket socket = new ServerSocket(3000); 

Aquí es mi método run() que esperar a que el cliente Socket cada vez que

public void run(){ 
     boolean dataRecieved = false; 
     char[] inputChars = new char[1024]; 
     int charsRead = 0; 

     while (!stopNow) { 
      try { 
       System.out.println("Listen To Clients:"); 

       // The ServerSocket has to listen the client each time. 
       InputStreamReader isr = new InputStreamReader(socket.accept().getInputStream()); 
       inputStream = new BufferedReader(isr); 

       //Read 1024 characters. Note: This will pause the thread when stream is empty. 
       System.out.println("Reading from stream:"); 

       if ((charsRead = inputStream.read(inputChars)) != -1) 
       { 
        System.out.println("Chars read from stream: " + charsRead); 
        System.out.println(inputChars); 
        System.out.flush(); 
       } 
      } 
      catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 
     } 
    } 

tiene otro pequeño error que detiene el código y eliminar la línea

charsRead = inputStream.read(inputChars); //<< THIS LINE IS PAUSING THE THREAD!> 

Debido esta línea se mueve en una declaración if.

+0

Es obvio por el hecho de que su código de E/S del servidor ya está ejecutando que ya tiene un ServerSocket. Tu comentario final es incomprensible. – EJP

0

Implemente un protocolo donde envíe la longitud de sus datos en sus encabezados para que el servidor/cliente sepa cuántos datos esperar.

+0

¿Por qué el voto a favor? – TheRealChx101

0
Socket socket; 

// Assuming socket is connected and not null 

if(socket != null){ 
    if(socket.getInputStream().available() > 0){ 
     byte[] buffer; 
     buffer = new byte[socket.getInputStream().available]; 
     socket.getInputStream().read(buffer); 

     // Your code here to deal with buffer. 

    } 
} 

Si desea escribir en el zócalo,

OutputStream mmOutStream; 
mmOutStream = socket.getOutputStream(); 

public void write(byte[] buffer) { 
    try { 
     mmOutStream.write(buffer); 
    } catch (IOException e) { 
     Log.e(TAG, "Exception during write ", e); 
    } 
} 
Cuestiones relacionadas