赞
踩
图1 |
图2 |
javax.comm.CommDriver
javax.comm.CommPort
javax.comm.ParallelPort
javax.comm.SerialPort
javax.comm.CommPortIdentifier
javax.comm.CommPortOwnershipListener
javax.comm.ParallelPortEvent
javax.comm.SerialPortEvent
javax.comm.ParallelPortEventListener (extends java.util.EventListener)
javax.comm.SerialPortEventListener (extends java.util.EventListener)
javax.comm.NoSuchPortException
javax.comm.PortInUseException
javax.comm.UnsupportedCommOperationException
在我的电脑上以上程序输出以下结果:
Enumeration en = CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier portId;
while (en.hasMoreElements())
{
portId = (CommPortIdentifier) en.nextElement();
/*如果端口类型是串口,则打印出其端口信息*/
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
System.out.println(portId.getName());
}
}
通过CommPortIdentifier的open方法可以返回一个CommPort对象。open方法有两个参数,第一个是String,通常设置为你的应用程序的名字。第二个参数是时间,即开启端口超时的毫秒数。当端口被另外的应用程序占用时,将抛出PortInUseException异常。
try {
CommPort serialPort = portId.open("My App" , 60 );
/*从端口中读取数据*/
InputStream input = serialPort.getInputStream();
input.read(...);
/*往端口中写数据*/
OutputStream output = serialPort.getOutputStream();
output.write(...)
...
} catch (PortInUseException ex)
{ ... }
public TestPort extend Thread
{
...
InputStream input = serialPort.getInputStream();
StringBuffer buf = new StringBuffer();
boolean stopped = false ;
...
public void run()
{
try {
while ( !stopped )
int ch = input.read();
if ( ch=='q' || ch=='Q' )
{
/*结束读取,关闭端口...*/
stopped = true ;
...
}
else
{
buf.append((char )ch);
...
}
} catch (InterruptedException e) { }
}
}
这个监听器只是简单打印每个发生的事件名称。而对于大多数应用程序来说,通常关心是DATA_AVAILABLE事件,当数据从外部设备传送到端口上来时将触发此事件。此时就可以使用前面提到过的方法,serialPort.getInputStream()来从InputStream中读取数据了。
public void MyPortListener implements SerialPortEventListener
{
public void serialEvent(SerialPortEvent evt)
{
switch (evt.getEventType())
{
case SerialPortEvent.CTS :
System.out.println("CTS event occured." );
break ;
case SerialPortEvent.CD :
System.out.println("CD event occured." );
break ;
case SerialPortEvent.BI :
System.out.println("BI event occured." );
break ;
case SerialPortEvent.DSR :
System.out.println("DSR event occured." );
break ;
case SerialPortEvent.FE :
System.out.println("FE event occured." );
break ;
case SerialPortEvent.OE :
System.out.println("OE event occured." );
break ;
case SerialPortEvent.PE :
System.out.println("PE event occured." );
break ;
case SerialPortEvent.RI :
System.out.println("RI event occured." );
break ;
case SerialPortEvent.OUTPUT_BUFFER_EMPTY :
System.out.println("OUTPUT_BUFFER_EMPTY event occured." );
break ;
case SerialPortEvent.DATA_AVAILABLE :
System.out.println("DATA_AVAILABLE event occured." );
int ch;
StringBuffer buf = new StringBuffer();
InputStream input = serialPort.getInputStream
try {
while ( (ch=input.read()) > 0 ) {
buf.append((char )ch);
}
System.out.print(buf);
} catch (IOException e) { }
break ;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。