⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serialconnection.java

📁 基于SUN的javacomm20-win32 API中的例子SerialDemo改进
💻 JAVA
字号:
package org.rien.rs;import gnu.io.*;import java.io.*;import java.awt.TextArea;import java.awt.TextField;import java.awt.event.*;import java.util.TooManyListenersException;public class SerialConnection implements SerialPortEventListener,		CommPortOwnershipListener {	private MyComm parent;	private TextField messageAreaOut;	private TextArea messageAreaIn;	private SerialParameters parameters;	private OutputStream os;	private InputStream is;	private KeyHandler keyHandler;	private CommPortIdentifier portId;	private SerialPort sPort;	private boolean open;	public SerialConnection(MyComm parent, SerialParameters parameters,			TextField messageAreaOut, TextArea messageAreaIn) {		this.parent = parent;		this.parameters = parameters;		this.messageAreaOut = messageAreaOut;		this.messageAreaIn = messageAreaIn;		open = false;	}	public void openConnection() throws SerialConnectionException {		try {			portId = CommPortIdentifier.getPortIdentifier(parameters					.getPortName());		} catch (NoSuchPortException e) {			throw new SerialConnectionException(e.getMessage());		}		try {			sPort = (SerialPort) portId.open("MyComm", 30000);		} catch (PortInUseException e) {			throw new SerialConnectionException(e.getMessage());		}		try {			setConnectionParameters();		} catch (SerialConnectionException e) {			sPort.close();			throw e;		}		try {			os = sPort.getOutputStream();			is = sPort.getInputStream();		} catch (IOException e) {			sPort.close();			throw new SerialConnectionException("打开i/o流错误!");		}		keyHandler = new KeyHandler(os);		messageAreaOut.addKeyListener(keyHandler);		try {			sPort.addEventListener(this);		} catch (TooManyListenersException e) {			sPort.close();			throw new SerialConnectionException("已经添加了监听器!");		}		sPort.notifyOnDataAvailable(true);		sPort.notifyOnBreakInterrupt(true);		try {			sPort.enableReceiveTimeout(30);		} catch (UnsupportedCommOperationException e) {		}		portId.addPortOwnershipListener(this);		open = true;	}	public void setConnectionParameters() throws SerialConnectionException {		int oldBaudRate = sPort.getBaudRate();		int oldDatabits = sPort.getDataBits();		int oldStopbits = sPort.getStopBits();		int oldParity = sPort.getParity();		int oldFlowControl = sPort.getFlowControlMode();		try {			sPort.setSerialPortParams(parameters.getBaudRate(), parameters					.getDatabits(), parameters.getStopbits(), parameters					.getParity());		} catch (UnsupportedCommOperationException e) {			parameters.setBaudRate(oldBaudRate);			parameters.setDatabits(oldDatabits);			parameters.setStopbits(oldStopbits);			parameters.setParity(oldParity);			throw new SerialConnectionException("不支持的参数错误!");		}		try {			sPort.setFlowControlMode(parameters.getFlowControlIn()					| parameters.getFlowControlOut());		} catch (UnsupportedCommOperationException e) {			throw new SerialConnectionException("不支持的流控制错误!");		}	}	public void closeConnection() {		if (!open) {			return;		}		messageAreaOut.removeKeyListener(keyHandler);		if (sPort != null) {			try {				os.close();				is.close();			} catch (IOException e) {				System.err.println(e);			}			sPort.close();			portId.removePortOwnershipListener(this);		}		open = false;	}	public void sendBreak() {		sPort.sendBreak(1000);	}	public boolean isOpen() {		return open;	}	public void serialEvent(SerialPortEvent e) {		StringBuffer inputBuffer = new StringBuffer();		int newData = 0;		switch (e.getEventType()) {		case SerialPortEvent.DATA_AVAILABLE:			inputBuffer.append("Recv:");			while (newData != -1) {				try {					newData = is.read();					if (newData == -1) {						break;					}					if ('\r' == (char) newData) {						inputBuffer.append('\n');					} else {						inputBuffer.append((char) newData);					}				} catch (IOException ex) {					System.err.println(ex);					return;				}			}			inputBuffer.append('\n');			byte[] data = new byte[10240];			try {					data = new String(inputBuffer).getBytes("iso-8859-1");				} catch (UnsupportedEncodingException e1) {					e1.printStackTrace();				}			messageAreaIn.append(new String(data));			break;		case SerialPortEvent.BI:			messageAreaIn.append("\n--- BREAK RECEIVED ---\n");		}	}	public void ownershipChange(int type) {		if (type == CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED) {			PortRequestedDialog prd = new PortRequestedDialog(parent);		}	}	class KeyHandler extends KeyAdapter {		OutputStream os;		public KeyHandler(OutputStream os) {			super();			this.os = os;		}		public void keyPressed(KeyEvent evt) {			// System.out.println(evt.getKeyCode());			if (evt.getKeyCode() == KeyEvent.VK_ENTER) {				// char newCharacter = evt.getKeyChar();				byte[] data = new byte[10240];				try {					data = messageAreaOut.getText().getBytes();					// os.write((int) newCharacter);					os.write(data);				} catch (IOException e) {					System.err.println("写入输出流错误: " + e);				}				messageAreaIn.append("Send:" + new String(data) + '\n');				messageAreaOut.setText("");			}		}	}}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -