嗨,我有这样的事情
package compot;
import java.util.Enumeration;
import gnu.io.*;
public class core {
private static SerialPort p;
/**
* @param args
*/
public static void main(String[] args)
{
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
System.out.println("start");
while(ports.hasMoreElements())
{
CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
System.out.print(port.getName() + " -> " + port.getCurrentOwner() + " -> ");
switch(port.getPortType())
{
case CommPortIdentifier.PORT_PARALLEL:
System.out.println("parell");
break;
case CommPortIdentifier.PORT_SERIAL:
//System.out.println("serial");
try {
p = (SerialPort) port.open("core", 1000);
int baudRate = 57600; // 57600bps
p.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (PortInUseException e) {
System.out.println(e.getMessage());
} catch (UnsupportedCommOperationException e) {
System.out.println(e.getMessage());
}
break;
}
}
System.out.println("stop");
}
}
但我不知道如何从端口读取?我读过this tutorial,但我不知道他们的意思是“演示申请”?
修改
OutputStream outStream = p.getOutputStream();
InputStream inStream = p.getInputStream();
BufferedReader in = new BufferedReader( new InputStreamReader(inStream));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
我添加了此代码,但我重新
稳定的图书馆 ========================================= Native lib Version = RXTX-2.1-7 Java lib Version = RXTX-2.1-7 start / dev / ttyUSB3 - >空值 - >底层输入流返回零字节停止
答案 0 :(得分:6)
这是你的代码吗?你到底想要做什么? :P
要从SerialPort读取,您需要声明此端口:
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("/dev/tty/USB0"); //on unix based system
然后在此端口上打开连接:
SerialPort serialPort = (SerialPort) portIdentifier.open("NameOfConnection-whatever", 0);
下一步是设置此端口的参数(如果需要):
serialPort.setSerialPortParams(38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
这是我的配置 - 您的配置可能会有所不同:)
现在您已准备好阅读此端口上的一些数据! 要获取数据,您需要获取serialPorts输入流并从中读取:
InputStream inputStream = serialPort.getInputStream();
while (active) {
try {
byte[] buffer = new byte[22];
while ((buffer[0] = (byte) inputStream.read()) != 'R') {
}
int i = 1;
while (i < 22) {
if (!active) {
break;
}
buffer[i++] = (byte) inputStream.read();
}
//do with the buffer whatever you want!
} catch (IOException ex) {
logger.error(ex.getMessage(), ex);
}
}
我在这里做的是使用它的read()
方法从输入流中读取。这将阻塞直到数据可用,或者如果到达流结束则返回-1。在这个例子中,我等到我得到一个'R'字符,然后将接下来的22个字节读入缓冲区。这就是你阅读数据的方式。
active
可以通过其他方法设置为false,从而结束阅读过程。希望这会有所帮助
答案 1 :(得分:2)
尝试使用
if (socketReader.ready()) {
}
以便套接字仅在缓冲流中有内容读取时才响应 所以异常永远不会发生。
答案 2 :(得分:0)
在你的try块中有这样的东西:
OutputStream outStream = p.getOutputStream();
InputStream inStream = p.getInputStream();