/******************************************
* 程序文件名稱(chēng):SendComm.java
* 功能:從串行口COM1中發(fā)送數據
******************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.comm.*;
class S_Frame extends Frame implements Runnable,ActionListener
{
/*檢測系統中可用的通訊端口類(lèi) */
static CommPortIdentifier portId;
/*Enumeration 為枚舉型類(lèi),在util中 */
static Enumeration portList;
OutputStream outputStream;
/*RS-232的串行口 */
SerialPort serialPort;
Thread readThread;
Panel p=new Panel();
TextField in_message=new TextField("打開(kāi)COM1,波特率9600,數據位8,停止位1.");
TextArea out_message=new TextArea();
Button btnOpen=new Button("打開(kāi)串口, 發(fā)送數據");
Button btnClose=new Button("關(guān)閉串口, 停止發(fā)送數據");
byte data[]=new byte[10240];
/*設置判斷要是否關(guān)閉串口的標志*/
boolean mark;
/*安排窗體*/
S_Frame()
{ super("串口發(fā)送數據");
setSize(200,200);
setVisible(true);
add(out_message,"Center");
add(p,"North");
p.add(btnOpen);
p.add(btnClose);
add(in_message,"South");
btnOpen.addActionListener(this);
btnClose.addActionListener(this);
} //R_Frame() end
/*點(diǎn)擊按扭打開(kāi)串口.*/
public void actionPerformed(ActionEvent event) {
if (event.getSource()==btnClose){
serialPort.close();//關(guān)閉串口
mark=true; //用于中止線(xiàn)程的run()方法
in_message.setText("串口COM1已經(jīng)關(guān)閉,停止發(fā)送數據.");
}
else { mark=false;
/*從文本區按字節讀取數據*/
data=out_message.getText().getBytes();
/*打開(kāi)串口*/
start();
in_message.setText("串口COM1已經(jīng)打開(kāi),正在每2秒鐘發(fā)送一次數據.....");
}
} //actionPerformed() end
/*打開(kāi)串口,并調用線(xiàn)程發(fā)送數據*/
public void start(){
/*獲取系統中所有的通訊端口 */
portList=CommPortIdentifier.getPortIdentifiers();
/* 用循環(huán)結構找出串口 */
while (portList.hasMoreElements()){
/*強制轉換為通訊端口類(lèi)型*/
portId=(CommPortIdentifier)portList.nextElement();
if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
if (portId.getName().equals("COM1")) {
/*打開(kāi)串口 */
try {
serialPort = (SerialPort) portId.open("ReadComm", 2000);
}
catch (PortInUseException e) { }
/*設置串口輸出流*/
try {
outputStream = serialPort.getOutputStream();
}
catch (IOException e) {}
} //if end
} //if end
} //while end
/*調用線(xiàn)程發(fā)送數據*/
try{
readThread = new Thread(this);
//線(xiàn)程負責每發(fā)送一次數據,休眠2秒鐘
readThread.start();
}
catch (Exception e) { }
} //start() end
/*發(fā)送數據,休眠2秒鐘后重發(fā)*/
public void run() {
/*設置串口通訊參數*/
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}
catch (UnsupportedCommOperationException e) { }
/*發(fā)送數據流(將數組data[]中的數據發(fā)送出去)*/
try {
outputStream.write(data);
}
catch (IOException e) { }
/*發(fā)送數據后休眠2秒鐘,然后再重發(fā)*/
try { Thread.sleep(2000);
if (mark)
{return; //結束run方法,導致線(xiàn)程死亡
}
start();
}
catch (InterruptedException e) { }
} //run() end
} //類(lèi)S_Frame end
public class SendComm
{public static void main(String args[])
{ S_Frame S_win=new S_Frame();
S_win.addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(0); }
});
S_win.pack();
}
}
/******************************************
* 程序文件名稱(chēng):ReadComm.java
* 功能:從串行口COM1中接收數據
******************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.comm.*;
class R_Frame extends Frame implements Runnable,ActionListener,SerialPortEventListener
{
/* 檢測系統中可用的通訊端口類(lèi) */
static CommPortIdentifier portId;
/* Enumeration 為枚舉型類(lèi),在java.util中 */
static Enumeration portList;
InputStream inputStream;
/* 聲明RS-232串行端口的成員變量 */
SerialPort serialPort;
Thread readThread;
String str="";
TextField out_message=new TextField("上面文本框顯示接收到的數據");
TextArea in_message=new TextArea();
Button btnOpen=new Button("打開(kāi)串口");
/*建立窗體*/
R_Frame()
{
super("串口接收數據");
setSize(200,200);
setVisible(true);
btnOpen.addActionListener(this);
add(out_message,"South");
add(in_message,"Center");
add(btnOpen,"North");
} //R_Frame() end
/*點(diǎn)擊按扭所觸發(fā)的事件:打開(kāi)串口,并監聽(tīng)串口. */
public void actionPerformed(ActionEvent event)
{
/*獲取系統中所有的通訊端口 */
portList=CommPortIdentifier.getPortIdentifiers();
/* 用循環(huán)結構找出串口 */
while (portList.hasMoreElements()){
/*強制轉換為通訊端口類(lèi)型*/
portId=(CommPortIdentifier)portList.nextElement();
if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
if (portId.getName().equals("COM1")) {
try {
serialPort = (SerialPort) portId.open("ReadComm", 2000);
out_message.setText("已打開(kāi)端口COM1 ,正在接收數據..... ");
}
catch (PortInUseException e) { }
/*設置串口監聽(tīng)器*/
try {
serialPort.addEventListener(this);
}
catch (TooManyListenersException e) { }
/* 偵聽(tīng)到串口有數據,觸發(fā)串口事件*/
serialPort.notifyOnDataAvailable(true);
} //if end
} //if end
} //while end
readThread = new Thread(this);
readThread.start();//線(xiàn)程負責每接收一次數據休眠20秒鐘
} //actionPerformed() end
/*接收數據后休眠20秒鐘*/
public void run() {
try {
Thread.sleep(20000);
}
catch (InterruptedException e) { }
} //run() end
/*串口監聽(tīng)器觸發(fā)的事件,設置串口通訊參數,讀取數據并寫(xiě)到文本區中*/
public void serialEvent(SerialPortEvent event) {
/*設置串口通訊參數:波特率、數據位、停止位、奇偶校驗*/
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}
catch (UnsupportedCommOperationException e) { }
byte[] readBuffer = new byte[20];
try {
inputStream = serialPort.getInputStream();
}
catch (IOException e) {}
try {
/* 從線(xiàn)路上讀取數據流 */
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
} //while end
str=new String(readBuffer);
/*接收到的數據存放到文本區中*/
in_message.append(str+"\n");
}
catch (IOException e) { }
} //serialEvent() end
} //類(lèi)R_Frame end
public class ReadComm
{
public static void main(String args[])
{
/* 實(shí)例化接收串口數據的窗體類(lèi) */
R_Frame R_win=new R_Frame();
/* 定義窗體適配器的關(guān)閉按鈕功能 */
R_win.addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(0); }
});
R_win.pack();
}
}
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1588546
聯(lián)系客服