Java外部设备编程:串口和并口通信详解
立即解锁
发布时间: 2025-08-18 02:37:43 阅读量: 4 订阅数: 11 

### Java 外部设备编程:串口和并口通信详解
在 Java 编程中,与外部设备进行通信是一个常见的需求,特别是通过串口和并口。本文将详细介绍在 Java 中实现串口和并口通信的几种方法,包括锁步模式、事件驱动模式、线程模式,并给出具体的代码示例。
#### 1. 锁步模式读写
当通信需求较为简单,例如向设备发送命令并获取响应时,可以采用锁步模式。这种模式下,通信双方像阅兵的士兵一样,步调一致,一方发送命令后,等待另一方的响应,然后再发送下一个命令。
**问题**:需要在端口上进行读写操作,且通信需求简单。
**解决方案**:使用读写调用。
**示例代码**:
```java
// CommPortModem.java
import java.awt.*;
import java.io.*;
import javax.comm.*;
import java.util.*;
public class CommPortModem extends CommPortOpen {
protected String response;
protected boolean debug = true;
public CommPortModem(Frame f)
throws IOException, NoSuchPortException,PortInUseException,
UnsupportedCommOperationException {
super(f);
}
protected void send(String s) throws IOException {
if (debug) {
System.out.print(">>> ");
System.out.print(s);
System.out.println( );
}
os.print(s);
os.print("\r\n");
if (!expect(s)) {
System.err.println("WARNING: Modem did not echo command.");
}
String junk = is.readLine( );
if (junk.length( ) != 0) {
System.err.print("Warning: unexpected response: ");
System.err.println(junk);
}
}
protected boolean expect(String exp) throws IOException {
response = is.readLine( );
if (debug) {
System.out.print("<<< ");
System.out.print(response);
System.out.println( );
}
return response.indexOf(exp) >= 0;
}
}
// CommPortDial.java
import java.io.*;
import javax.comm.*;
import java.util.*;
public class CommPortDial extends CommPortModem {
protected static String number = "000-0000";
public static void main(String[] ap)
throws IOException, NoSuchPortException,PortInUseException,
UnsupportedCommOperationException {
if (ap.length == 1)
number = ap[0];
new CommPortDial( ).converse( );
System.exit(0);
}
public CommPortDial( )
throws IOException, NoSuchPortException, PortInUseException,
UnsupportedCommOperationException {
super(null);
}
protected void converse( ) throws IOException {
String resp;
send("ATZ");
expect("OK");
send("ATDT" + number);
expect("OK");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// nothing to do
}
is.close( );
os.close( );
}
}
```
**操作步骤**:
1. 创建 `CommPortModem` 类,该类继承自 `CommPortOpen`,并添加 `send` 和 `expect` 方法用于与 Hayes 类型的调制解调器进行通信。
2. 创建 `CommPortDial` 类,继承自 `CommPortModem`,用于初始化调制解调器并拨打电话号码。
3. 在 `main` 方法中,根据命令行参数设置电话号码,然后调用 `converse` 方法进行通信。
#### 2. 事件驱动模式读写
当连接建立后,无法确定读写顺序时,锁步模式可能会导致死锁。此时,可以采用事件驱动模式或线程模式。事件驱动模式通过 Java 通信事件通知端口何时可以进行读写操作。
**问题**:连接建立后,不知道读写顺序。
**解决方案**:使用 Java 通信事件通知数据可用,或使用线程。
**示例代码**:
```java
// SerialReadByEvents.java
import java.awt.*;
import java.io.*;
import javax.comm.*;
import java.util.*;
public class SerialReadByEvents extends CommPortOpen
implements SerialPortEventListener {
public static void main(String[] argv)
throws IOException, NoSuchPortException, PortInUseException,
UnsupportedCommOperationException {
new SerialReadByEvents(null).converse( );
}
public SerialReadByEvents(Frame f)
throws IOException, NoSuchPortException, PortInUseException,
UnsupportedCommOperationException {
super(f);
}
protected BufferedReader ifile;
protected void converse( ) throws IOException {
if (!(thePort instanceof SerialPort)) {
System.err.println("But I wanted a SERIAL port!");
System.exit(1);
}
((SerialPort)thePort).notifyOnDataAvailable(true);
try {
((SerialPort)thePort).addEventListener(this);
} catch (TooManyListenersException ev) {
System.err.println("Too many listeners(!) " + ev);
System.exit(0);
}
ifile = new BufferedReader(new InputStreamReader(is));
}
public void serialEvent(SerialPortEvent ev) {
String line;
try {
line = ifile.readLine( );
if (line == null) {
System.out.println("EOF on serial port.");
System.exit(0);
}
os.println(line);
} catch (IOException ex) {
System.err.println("IO Error " + ex);
}
}
}
// SerialLogger.java
import java.io.*;
import javax.comm.*;
import java.util.*;
public class SerialLogger {
public static void main(String[] argv)
throws IOException, NoSuchPortException, PortInUseException,
UnsupportedCommOperationException {
new SerialLogger( );
}
public SerialLogger( )
throws IOException, NoSuchPortException, PortInUseException,
UnsupportedCommOperationException {
Enumeration pList = CommPortIdentifier.getPortIdentifiers( );
while (pList.hasMoreElements( )) {
CommPortIdentifier cpi = (CommPortIdentifier)pList.nextElement( );
String name = cpi.getName( );
System.out.print("Port " + name + " ");
if (cpi.getPortType( ) == CommPortIdentifier.PORT_S
```
0
0
复制全文
相关推荐










