我有一个 servlet 上下文监听器,其中有一个串行端口监听器。在此监听器中,我通过以下方式保存来自串行端口的字节:
public void contextInitialized(ServletContextEvent contextEvent){
context = contextEvent.getServletContext();
serial = SerialFactory.createInstance();
serial.open(Serial.DEFAULT_COM_PORT, 19200);
serial.addListener(new SerialDataListener(){
@Override
public void dataReceived(SerialDataEvent arg0) {
private byte[] serialDataByte;
serialDataByte = arg0.getData().getBytes();
context.setAttribute("serialData", serialDataByte);
seriale.write(serialDataByte); //the echo on serial port show me the right bytes
}
});
}
在我的 Controller 上,我通过以下方式访问串行端口数据:
private byte[] temp;
temp = (byte[]) getServletContext().getAttribute("serialData");
for(int i=0; i<temp.length;i++){
output.println(Integer.toHexString(temp[i] & 0x00FF));
}
我将这个字节数组发送到串行端口:
aa 7f 40 a 72 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 fe 1a
长度为 69。 有时在我的临时数组中我只有原始数组的一小部分,有时:
aa 7f 40 a 72 0 0 0 0 0 0 0 0 0 0
有时:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 fe 1a
有时是 69 字节的正确数组。 如何将从串行端口获取的准确数据传递给 Controller ? 提前致谢
最佳答案
如果有更多数据进入该端口,此代码将覆盖您最初在 serialData
上下文属性中拥有的数据。因此,仅在属性存在时才写入,并考虑在初始 dataRecieved()
调用后关闭端口。
serial.addListener(new SerialDataListener(){
@Override
public void dataReceived(SerialDataEvent arg0) {
private byte[] serialDataByte;
if (context.getAttribute("serialData") == null) {
serialDataByte = arg0.getData().getBytes();
context.setAttribute("serialData", serialDataByte);
seriale.write(serialDataByte); // I assume this is only for debugging
// and also supposed to be `serial`
serial.close();
}
}
});
关于java - 将字节数组从 servlet 监听器传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15076469/