六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 39|回复: 0

java串口 来电显示

[复制链接]

升级  66%

7

主题

7

主题

7

主题

童生

Rank: 1

积分
33
 楼主| 发表于 2013-1-15 02:45:40 | 显示全部楼层 |阅读模式
一.使用sun公司的comm.jar
  1.配置(下载comm.jar包http://code.google.com/p/smslib/downloads/detail?name=javacomm20-win32.zip&can=2&q=)
    (1).将包下的javax.comm.properties放到jdk home/jre/lib下
    (2).将包下的win32com.dll放到jdk home/jre/bin下(也可以放到windows下的system32下)
    (3).将comm.jar放到jdk home/jre/lib/ext下
  2.java代码
package comm;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import java.util.TooManyListenersException;import javax.comm.CommDriver;import javax.comm.CommPortIdentifier;import javax.comm.PortInUseException;import javax.comm.SerialPort;import javax.comm.SerialPortEvent;import javax.comm.SerialPortEventListener;import javax.comm.UnsupportedCommOperationException;public class SimpleWrite {public static void main(String[] args) {// System.loadLibrary("win32com");CommDriver driver = null;String driverName = "com.sun.comm.Win32Driver";// SerialPort sPort = (SerialPort) driver.getCommPort("COM4",// CommPortIdentifier.PORT_SERIAL);Enumeration<CommPortIdentifier> enumeration = CommPortIdentifier.getPortIdentifiers();while (enumeration.hasMoreElements()) {CommPortIdentifier portId = enumeration.nextElement();System.out.println(portId.getName() + "============");if (portId.getName().equals("COM1")) {try {System.out.println("jjj");final SerialPort sp = (SerialPort) portId.open("SimpleWrite", 1000);sp.setSerialPortParams(2400, SerialPort.DATABITS_8,SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);final InputStream is = sp.getInputStream();final OutputStream os = sp.getOutputStream();os.write(100);os.flush();os.close();//Set notifyOnDataAvailable to true to allow event driven input.   sp.notifyOnDataAvailable(true);// Set notifyOnBreakInterrup to allow event driven break// handling.sp.notifyOnBreakInterrupt(true);// Set receive timeout to allow breaking out of polling loop// during input handling.sp.enableReceiveTimeout(30);final StringBuffer linkWgt = new StringBuffer();// 存放获取的数据sp.addEventListener(new SerialPortEventListener() {@Overridepublic void serialEvent(SerialPortEvent e) {int newData = 0;// Determine type of event.switch (e.getEventType()) {// Read data until -1 is returned. If \r is received// substitute// \n for correct newline handling.case SerialPortEvent.DATA_AVAILABLE:while (newData != -1) {try {newData = is.read();if (newData == -1) {break;}if ('\r' == (char) newData) {} else {linkWgt.append((char) newData);}} catch (IOException ex) {System.err.println(ex);return;}}// Append received data to messageAreaIn.try {System.out.println("linkWgt ---------
ǩ
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表