inputstream.available()为0时总是

问题描述:

我没有什么是发生在我的代码的想法。我没有得到任何错误,也没有回应。我正在将数据写入串行端口,并通过激活port.notifyOnDataAvailable(true);等待响应,但未触发此事件,并且inputstream.available()始终返回0。什么可能是错误的?我在linux中使用RXTX。inputstream.available()为0时总是

EDIT

package testConn; 
import forms_helper.global_variables; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.PrintStream; 
import java.io.UnsupportedEncodingException; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.comm.*; 
import java.util.*; 
/** Check each port to see if it is open. **/ 
public class openPort implements SerialPortEventListener { 

    static Enumeration portList; 
    static CommPortIdentifier portId; 
    static String messageString; 
    public static SerialPort serialPort; 
    static OutputStream outputStream; 
    InputStream inputStream; 
    static boolean outputBufferEmptyFlag = false; 
    private BufferedReader is; 
    private PrintStream os; 

    public void open() { 
     Enumeration port_list = CommPortIdentifier.getPortIdentifiers(); 

     while (port_list.hasMoreElements()) { 
      // Get the list of ports 
      CommPortIdentifier port_id = (CommPortIdentifier) port_list.nextElement(); 
      if (port_id.getName().equals("/dev/ttyS1")) { 

       // Attempt to open it 
       try { 
        SerialPort port = (SerialPort) port_id.open("PortListOpen", 20000); 
        System.out.println("Opened successfully:"+port); 
        try { 
         int baudRate = 9600; // 
         port.setSerialPortParams(
           baudRate, 
           SerialPort.DATABITS_7, 
           SerialPort.STOPBITS_1, 
           SerialPort.PARITY_EVEN); 
         port.setDTR(true); 


         port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE); 

         System.out.println("properties are set"); 
        } catch (UnsupportedCommOperationException e) { 
         System.out.println(e); 
        } 
        try { 
         //input = new SerialReader(in); 
         port.addEventListener(this); 
         System.out.println("listeners attached" + this); 
        } catch (TooManyListenersException e) { 
         System.out.println("too many listeners"); 
        } 
        port.notifyOnDataAvailable(true); 

        //port.notifyOnOutputEmpty(true); 
        //sendMessage(port,"@PL"); 
        //port.close(); 
        try { 
         is = new BufferedReader(new InputStreamReader(port.getInputStream())); 
        } catch (IOException e) { 
         System.err.println("Can't open input stream: write-only"); 
         is = null; 
        } 
        try { 
         os = new PrintStream(port.getOutputStream(), true); 
        } catch (IOException ex) { 
         Logger.getLogger(openPort.class.getName()).log(Level.SEVERE, null, ex); 
        } 

        try { 
         inputStream = port.getInputStream(); 
         System.out.println("inputstream" + inputStream.available()); 
         outputStream = (OutputStream) port.getOutputStream(); 
         os = new PrintStream(port.getOutputStream(), true, "US-ASCII"); 


        } catch (IOException e) { 
         System.out.println(e); 
        } 

        //set the created variables to global variables 
        global_variables.port = port; 
        global_variables.inputStream = inputStream; 
        System.out.println(inputStream); 
        System.out.println(outputStream); 
        global_variables.outputStream = outputStream; 
        global_variables.os = os; 
       } catch (PortInUseException pe) { 
        System.out.println("Open failed"); 
        String owner_name = port_id.getCurrentOwner(); 
        if (owner_name == null) { 
         System.out.println("Port Owned by unidentified app"); 
        } else // The owner name not returned correctly unless it is 
        // a Java program. 
        { 
         System.out.println(" " + owner_name); 
        } 
       } 
      } 
     } 
    } 

    public static void sendMessage(SerialPort port, String msg) { 
     if (port != null) { 
       System.out.println(msg); 
      try { 
       byte[] bytes = msg.getBytes("US-ASCII"); 
       try { 
        global_variables.outputStream.write(bytes); 
        System.out.println(bytes.length); 
        global_variables.outputStream.flush(); 
       } catch (IOException ex) { 
        Logger.getLogger(openPort.class.getName()).log(Level.SEVERE, null, ex); 
       } 
      } catch (UnsupportedEncodingException ex) { 
       Logger.getLogger(openPort.class.getName()).log(Level.SEVERE, null, ex); 
      } 
       System.out.println("Opened successfully:"+msg.getBytes()); 
       //global_variables.outputStream.write(msg.getBytes()); 
       //global_variables.outputStream.flush(); 
       //global_variables.os.print(msg); 
       System.out.println(global_variables.outputStream); 
       try { 
        Thread.sleep(2000); // Be sure data is xferred before closing 
        System.out.println("read called"); 
        //SimpleRead read = new SimpleRead(); 
        //int read = global_variables.inputStream.read(); 
        //System.out.println("read call ended"+read); 
       } catch (Exception e) { 
       } 

     } 
    } 

    public void serialEvent(SerialPortEvent event) { 
     System.out.println(event.getEventType()); 
     String line; 
       try { 
        line = is.readLine(); 
        if (line == null) { 
         System.out.println("EOF on serial port."); 
         System.exit(0); 
        } 
        os.println(line); 
       } catch (IOException ex) { 
        System.err.println("IO Error " + ex); 
       } 
     switch (event.getEventType()) { 
      /* 
      case SerialPortEvent.BI: 

      case SerialPortEvent.OE: 

      case SerialPortEvent.FE: 

      case SerialPortEvent.PE: 

      case SerialPortEvent.CD: 

      case SerialPortEvent.CTS: 

      case SerialPortEvent.DSR: 

      case SerialPortEvent.RI: 


      case SerialPortEvent.OUTPUT_BUFFER_EMPTY: 
      System.out.println("event.getEventType()"); 
      break; 
      * 
      */ 

      case SerialPortEvent.DATA_AVAILABLE: 
       System.out.println("inside event handler data available"); 
       byte[] readBuffer = new byte[20]; 


       try { 
        while (inputStream.available() > 0) { 
         int numBytes = inputStream.read(readBuffer); 
        } 
        System.out.print(new String(readBuffer)); 
        System.exit(1); 
       } catch (IOException e) { 
        System.out.println(e); 
       } 

       break; 
     } 
    } 
} // PortListOpen 

我正在打开上main方法的端口并在应用程序中的按钮点击事件发送消息。

+0

你能展示一些简单的代码来重现问题吗? – sarnold 2011-04-28 23:27:53

+0

@sarnold:检查我的编辑... – Deepak 2011-04-28 23:31:19

+0

更好:)谢谢;你从System.out.println(event.getEventType())得到了什么输出;'?此外,我会发现串行设备有一个'available()'方法有点奇怪,在[示例](http://rxtx.qbang.org/wiki/index.php/Event_based_two_way_Communication)只是'阅读()',看看它是否有数据.. – sarnold 2011-04-29 00:03:34

.available()不能用于进程间通信(包括串口),s它只会检查当前进程中是否有可用的数据(在输入缓冲区中)。

在串行通信中,当您发送messaga,然后立即打电话available()你将主要得0为串行端口并没有针对任何数据回复。

的解决方案是使用一个单独的线程阻塞read()(与interrupt()结束它):

Thread interrupt not ending blocking call on input stream read

+0

但是不会SerialPortEventListener在这里为我们提供工作吗?而不是使用单独的线程? – Deepak 2011-04-28 23:59:23

要部分地回答你的问题。

从javadocs中

类 InputStream的可用方法总是返回0

http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html#available()

因此如预期的那部分的至少

+0

这是否意味着有来无反应从我正在写邮件的终端出来? – Deepak 2011-04-28 23:37:20

+2

InputStream是一个抽象类,所以你总是处理一些可能覆盖'available'的具体子类。 – 2011-04-29 08:57:48

+0

-1类InputStream和对象inputstream之间有区别。 – 2013-01-14 20:10:02

通过使用你抑制你需要了解任何请求例外一个PrintStream /响应场景。

最有可能你还没有发出任何东西。

+0

但是当我打电话给sendMessage(端口,消息)的东西将被写入端口仪式? – Deepak 2011-04-29 00:16:29

+0

@Deepak:如果您通过PrintWriter编写并且出现异常,则不行。 PrintWriter吞食异常。看到Javadoc。在同一底层数据流中使用多个数据流也是非常糟糕的做法,实际上是不正确的,就像你在这里做的那样,尤其是当它们中的一个或多个被缓冲时。我也不知道你为什么要创建PrintStream'os'两次。您需要使用来自端口的单个输入流和单个输出流简化所有这些操作。 – EJP 2011-04-29 00:36:57

+0

好吧,我会改变这一点,并检查它是否工作 – Deepak 2011-04-29 01:00:10