java se 没有连串口的组件,通过mina
mina的简介:
https://www.oschina.net/p/mina?hmsr=aladdin1e1
核心库:
public final class SerialConnector extends AbstractIoConnector
public interface IoHandler
public class SerialAddress extends SocketAddress
大概流程如下:
SerialConnector把IoHandler设置为自己的处理Handler,并且连接指定的SerialAddress。连接完成后,IoHandler中可以通过sessionOpened得到串口连接的sesseion,可以通过session发送数据。
main代码如下:
//创建串口连接
SerialConnector connector = new SerialConnector();
//绑定处理handler
COMHandler comHandler=new COMHandler();//COMHandler是实现IoHandler的子类
connector.setHandler(comHandler);
try{
//配置串口连接,参数自己用实际的字符串代替
SerialAddress address = new SerialAddress((String) hs.get("COMM.PortName"),
Integer.parseInt((String) hs.get("COMM.BaudRate")), DataBits.DATABITS_8, StopBits.BITS_1, Parity.NONE,
FlowControl.NONE);
connector.connect(address);
} catch (Throwable e) {
throw new RuntimeException("打开串口失败", e);
}
comHandler().getSession().write("abcd");//写数据
COMHandler 代码如下:
public class COMHandler implements IoHandler
{
IoSession session=null;
@Override
public void sessionCreated(IoSession session) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void sessionOpened(IoSession session) throws Exception {
// TODO Auto-generated method stub
this.session=session;
}
@Override //读数据
public void messageReceived(IoSession session, Object message) throws Exception {
// TODO Auto-generated method stub
}
//......
}
-------------------------------------------------------------------
完整的类:
-------------------------------------------------------------------
pom.xml
<!-- https://mvnrepository.com/artifact/org.rxtx/rxtx -->
<dependency>
<groupId>org.rxtx</groupId>
<artifactId>rxtx</artifactId>
<version>2.1.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.mina/mina-core -->
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId>
<version>2.0.2</version&g