InputStream inputStream; SerialPort serialPort; Thread readThread; public static void main(String[] args) { try{ portId = CommPortIdentifier.getPortIdentifier("COM2"); }catch(Exception e){ e.printStackTrace(); } SimpleRead reader = new SimpleRead(); System.out.println ("读到的信息:"); int i; try{ while((i = reader.inputStream.read()) != -1){ System.out.println ((char)i); } }catch(Exception e){ e.printStackTrace(); } } public SimpleRead() { try { serialPort = (SerialPort) portId.open("SimpleReadApp", 2000); } catch (PortInUseException e) { e.printStackTrace(); } try { inputStream = serialPort.getInputStream(); } catch (IOException e) { e.printStackTrace(); } try { serialPort.addEventListener(this); } catch (TooManyListenersException e) {} serialPort.notifyOnDataAvailable(true); try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) {} readThread = new Thread(this); readThread.start(); } public void run() { try { Thread.sleep(20000); } catch (InterruptedException e) {} } public void serialEvent(SerialPortEvent event) { switch(event.getEventType()) { case SerialPortEvent.BI: case SerialPortEvent.OE: case SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD: case SerialPortEvent.CTS: case SerialPortEvent.DSR: case SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE: byte[] readBuffer = new byte[20]; try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); } System.out.print(new String(readBuffer)); } catch (IOException e) {} break; } } }在COM1上写,在COM2读,两个端口用串口线直接连接起来了,写的程序运行完毕了,打印出来了(写入COM1 信息成功).可读的程序一直停在read()那里,什么都没读出来,我已经试过在写的程序用一个无限循环不停的写,结果也一样.
com1 com2连接的时候 油三根数据线 2-----3 3-----2 5-----5
我是买的一根标准的串口线,两头是COM接口的线直接相连的.另外,对上面的读的程序中的事件监听这一段不太理解,是不是一有数据来,那个方法里就会处理? public void serialEvent(SerialPortEvent event) { switch(event.getEventType()) { case SerialPortEvent.BI: case SerialPortEvent.OE: case SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD: case SerialPortEvent.CTS: case SerialPortEvent.DSR: case SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE: byte[] readBuffer = new byte[20]; try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); } System.out.print(new String(readBuffer)); } catch (IOException e) {} break; } }
TO bonwei(阿邦) 兄我现在也是这样在测试,试了好几台机,一边用我上面的两个程序或读或写,一边用串品调试程序在或读或写,可就是不出东西.难道是我的那根串口线有问题吗?我中午再去买机线试试看,阿邦兄再帮我看看我上面的贴出来的两个读写串口的代码有没有问题了,或者把你的测试用的读写串口的代码发一份给我看看,非常感谢.这个问题搞定后,我再开一个100分贴给你,谢谢!
to cql0007(蓝月) 我觉得可能不是硬件的问题,我写了一段代码,使用一个线程向COM1写,一个线程从COM1读,一样的读不出来。我COM1连接的是手机。但是用超级终端读写都没问题。不知道是什么原因
package serial; import java.io.*; import java.util.*; import javax.comm.*; /** * * This bean provides some basic functions to implement full dulplex * information exchange through the srial port. * */ public class SerialBean { static String PortName; CommPortIdentifier portId; SerialPort serialPort; static OutputStream out; static InputStream in; SerialBuffer SB; ReadSerial RT; /** * * Constructor * * @param PortID the ID of the serial to be used. 1 for COM1, * 2 for COM2, etc. * */ public SerialBean(int PortID) { PortName = "COM" + PortID; } /** * * This function initialize the serial port for communication. It startss a * thread which consistently monitors the serial port. Any signal capturred * from the serial port is stored into a buffer area. * */ public int Initialize() { int InitSuccess = 1; int InitFail = -1; try { portId = CommPortIdentifier.getPortIdentifier(PortName); try { serialPort = (SerialPort) portId.open("Serial_Communication", 2000); } catch (PortInUseException e) { return InitFail; } //Use InputStream in to read from the serial port, and OutputStream //out to write to the serial port. try { in = serialPort.getInputStream(); out = serialPort.getOutputStream(); } catch (IOException e) { return InitFail; } //Initialize the communication parameters to 9600, 8, 1, none. try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) { return InitFail; } } catch (NoSuchPortException e) { return InitFail; } // when successfully open the serial port, create a new serial buffer, // then create a thread that consistently accepts incoming signals from // the serial port. Incoming signals are stored in the serial buffer. SB = new SerialBuffer(); RT = new ReadSerial(SB, in); RT.start(); // return success information return InitSuccess; } /** * * This function returns a string with a certain length from the incomin * messages. * * @param Length The length of the string to be returned. * */ public String ReadPort(int Length) { String Msg; Msg = SB.GetMsg(Length); return Msg; } /** * * This function sends a message through the serial port. * * @param Msg The string to be sent. * */ public void WritePort(String Msg) { int c; try { for (int i = 0; i < Msg.length(); i++) out.write(Msg.charAt(i)); } catch (IOException e) {} } /** * * This function closes the serial port in use. * */ public void ClosePort() { RT.stop(); serialPort.close(); } }
package serial; /** * * This class implements the buffer area to store incoming data from the serial * port. * */ public class SerialBuffer { private String Content = ""; private String CurrentMsg, TempContent; private boolean available = false; private int LengthNeeded = 1; /** * * This function returns a string with a certain length from the incomin * messages. * * @param Length The length of the string to be returned. * */ public synchronized String GetMsg(int Length) { LengthNeeded = Length; notifyAll(); if (LengthNeeded > Content.length()) { available = false; while (available == false) { try { wait(); } catch (InterruptedException e) { } } } CurrentMsg = Content.substring(0, LengthNeeded); TempContent = Content.substring(LengthNeeded); Content = TempContent; LengthNeeded = 1; notifyAll(); return CurrentMsg; } /** * * This function stores a character captured from the serial port to the * buffer area. * * @param t The char value of the character to be stored. * */ public synchronized void PutChar(int c) { Character d = new Character((char) c); Content = Content.concat(d.toString()); if (LengthNeeded < Content.length()) { available = true; } notifyAll(); } }
package serial; import java.io.*; /** * * This class reads message from the specific serial port and save * the message to the serial buffer. * */ public class ReadSerial extends Thread { private SerialBuffer ComBuffer; private InputStream ComPort; /** * * Constructor * * @param SB The buffer to save the incoming messages. * @param Port The InputStream from the specific serial port. * */ public ReadSerial(SerialBuffer SB, InputStream Port) { ComBuffer = SB; ComPort = Port; } public void run() { int c; try { while (true) { c = ComPort.read(); ComBuffer.PutChar(c); } } catch (IOException e) {} } }
写:
import java.io.*;
import java.util.*;
import javax.comm.*;public class SimpleWrite {
static CommPortIdentifier myPort;
static String messageString = "Hello, world!\n";
static SerialPort serialPort;
static OutputStream outputStream; public static void main(String[] args) {
try{
myPort = CommPortIdentifier.getPortIdentifier("COM1");
}catch(Exception e){
e.printStackTrace();
} try{
serialPort = (SerialPort)myPort.open("SimpleWriteApp", 2000);
} catch (PortInUseException e) {
e.printStackTrace();
}
try{
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
try {
outputStream.write(messageString.getBytes());
System.out.println ("写入" + myPort.getName() + "信息成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
-------------------------------------------------------
这是读端口代码:
import java.io.*;
import java.util.*;
import javax.comm.*;public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
InputStream inputStream;
SerialPort serialPort;
Thread readThread; public static void main(String[] args) {
try{
portId = CommPortIdentifier.getPortIdentifier("COM2");
}catch(Exception e){
e.printStackTrace();
}
SimpleRead reader = new SimpleRead();
System.out.println ("读到的信息:");
int i;
try{
while((i = reader.inputStream.read()) != -1){
System.out.println ((char)i);
}
}catch(Exception e){
e.printStackTrace();
}
} public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {
e.printStackTrace();
}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
} public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {}
} public void serialEvent(SerialPortEvent event) {
switch(event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20]; try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
System.out.print(new String(readBuffer));
} catch (IOException e) {}
break;
}
}
}在COM1上写,在COM2读,两个端口用串口线直接连接起来了,写的程序运行完毕了,打印出来了(写入COM1 信息成功).可读的程序一直停在read()那里,什么都没读出来,我已经试过在写的程序用一个无限循环不停的写,结果也一样.
2-----3
3-----2
5-----5
public void serialEvent(SerialPortEvent event) {
switch(event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20]; try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
System.out.print(new String(readBuffer));
} catch (IOException e) {}
break;
}
}
还不如直接参考sun的东西。
outputStream.write(messageString.getBytes());
之后加上
outputStream.flush();俺没试过,不知道行不行。
硬件问题其实我已经试过了好几台机了,本想用超级终端来试试,可那个东西搞了半天不知怎么发消息,上网查资料都是用超级终端来连接MODEM的,不是我的串口线的这种.现在这样直接用我的上面的程序去试,就搞不清是程序的问题还是连接的问题了.不过我看到CSDN上以前很多老兄都搞过这个问题,都说一下就搞定了,看来搞定它问题应该是不太大的,只是我现在不知被拌在哪一块,怎么都过不去,郁闷.另外,哪位老兄知不知道,这个包支不支持RS-485的串口啊?这方面的资料我也没查到.
读端口的程序我做过,不过没有象你那样用数据线做测试
我是通过端口操作的GPRS Modem 发短信
你的邮件我收到了,谢谢.你发的那个串口调试器我昨天也下载过一个用过了.
那种串口调试的工具我试了几个,不过没有一个试出个正常的结果.那种工具是不是这样的:
在COM1端口启动一个调试程序,在COM2端口启动另一个调试程序,用线将COM1和COM2连接起来,然后在COM1口的程序发出信息,COM2口的程序就能自动的立即收到?我是什么信息都没收到...
感谢另外几位老兄的回贴,现在最郁闷的不知怎么个调试法,第一步都没通过,所以程序的别的问题也还不知道...........
我觉得可能不是硬件的问题,我写了一段代码,使用一个线程向COM1写,一个线程从COM1读,一样的读不出来。我COM1连接的是手机。但是用超级终端读写都没问题。不知道是什么原因
http://www-900.ibm.com/developerWorks/cn/java/j-i-barcd/index.shtml
先测试一下两个串口是不是能够正常收发你老人家就不能弄个MODEM吗?!!
import java.io.*;
import java.util.*;
import javax.comm.*;
/**
*
* This bean provides some basic functions to implement full dulplex
* information exchange through the srial port.
*
*/
public class SerialBean
{
static String PortName;
CommPortIdentifier portId;
SerialPort serialPort;
static OutputStream out;
static InputStream in;
SerialBuffer SB;
ReadSerial RT;
/**
*
* Constructor
*
* @param PortID the ID of the serial to be used. 1 for COM1,
* 2 for COM2, etc.
*
*/
public SerialBean(int PortID)
{
PortName = "COM" + PortID;
}
/**
*
* This function initialize the serial port for communication. It startss a
* thread which consistently monitors the serial port. Any signal capturred
* from the serial port is stored into a buffer area.
*
*/
public int Initialize()
{
int InitSuccess = 1;
int InitFail = -1;
try
{
portId = CommPortIdentifier.getPortIdentifier(PortName);
try
{
serialPort = (SerialPort)
portId.open("Serial_Communication", 2000);
} catch (PortInUseException e)
{
return InitFail;
}
//Use InputStream in to read from the serial port, and OutputStream
//out to write to the serial port.
try
{
in = serialPort.getInputStream();
out = serialPort.getOutputStream();
} catch (IOException e)
{
return InitFail;
}
//Initialize the communication parameters to 9600, 8, 1, none.
try
{
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e)
{
return InitFail;
}
} catch (NoSuchPortException e)
{
return InitFail;
}
// when successfully open the serial port, create a new serial buffer,
// then create a thread that consistently accepts incoming signals from
// the serial port. Incoming signals are stored in the serial buffer.
SB = new SerialBuffer();
RT = new ReadSerial(SB, in);
RT.start();
// return success information
return InitSuccess;
}
/**
*
* This function returns a string with a certain length from the incomin
* messages.
*
* @param Length The length of the string to be returned.
*
*/
public String ReadPort(int Length)
{
String Msg;
Msg = SB.GetMsg(Length);
return Msg;
}
/**
*
* This function sends a message through the serial port.
*
* @param Msg The string to be sent.
*
*/
public void WritePort(String Msg)
{
int c;
try
{
for (int i = 0; i < Msg.length(); i++)
out.write(Msg.charAt(i));
} catch (IOException e) {}
}
/**
*
* This function closes the serial port in use.
*
*/
public void ClosePort()
{
RT.stop();
serialPort.close();
}
}
/**
*
* This class implements the buffer area to store incoming data from the serial
* port.
*
*/
public class SerialBuffer
{
private String Content = "";
private String CurrentMsg, TempContent;
private boolean available = false;
private int LengthNeeded = 1;
/**
*
* This function returns a string with a certain length from the incomin
* messages.
*
* @param Length The length of the string to be returned.
*
*/
public synchronized String GetMsg(int Length)
{
LengthNeeded = Length;
notifyAll();
if (LengthNeeded > Content.length())
{
available = false;
while (available == false)
{
try
{
wait();
} catch (InterruptedException e) { }
}
}
CurrentMsg = Content.substring(0, LengthNeeded);
TempContent = Content.substring(LengthNeeded);
Content = TempContent;
LengthNeeded = 1;
notifyAll();
return CurrentMsg;
}
/**
*
* This function stores a character captured from the serial port to the
* buffer area.
*
* @param t The char value of the character to be stored.
*
*/
public synchronized void PutChar(int c)
{
Character d = new Character((char) c);
Content = Content.concat(d.toString());
if (LengthNeeded < Content.length())
{
available = true;
}
notifyAll();
}
}
import java.io.*;
/**
*
* This class reads message from the specific serial port and save
* the message to the serial buffer.
*
*/
public class ReadSerial extends Thread
{
private SerialBuffer ComBuffer;
private InputStream ComPort;
/**
*
* Constructor
*
* @param SB The buffer to save the incoming messages.
* @param Port The InputStream from the specific serial port.
*
*/
public ReadSerial(SerialBuffer SB, InputStream Port)
{
ComBuffer = SB;
ComPort = Port;
}
public void run()
{
int c;
try
{
while (true)
{
c = ComPort.read();
ComBuffer.PutChar(c);
}
} catch (IOException e) {}
}
}