본문 바로가기
프로그래밍/java

자바 시리얼 통신 설명 자료[펌]

by Super User 2009. 6. 10.

RS232C Serial Communication Programming

자바에서 RS232 통신을 하기 위해서 javax.comm 패키지를 import 한다. 소켓 통신보다는 프로그램에서 설정해야 할 것이 다소 많다. 하지만 RS232 통신도 I/O 기반이기 때문에 통신부분은 소켓 통신과 똑같다.

RS232 통신하려면 Serial port 또는 parallel port를 인식해야 한다. javax.comm.commPortIdentifier 클래스는 시스템에 이용 가능한 포트 리스트(port list)를 만들고, 어떤 프로그램이 포트를 가지고 있는지를 알아내고, 포트를 제어하고, 포트를 열어서 I/O를 실행할 수 있게 하는 메쏘드(method)를 가지고 있다. 포트에 대한 식별자를 찾아야 하는데, 포트 식별자(port identifier)는 물리적 계층과 밀접하게 결합되어 있기 때문에 쉽게 commPortIdentifier 객체를 생성할 수 없다. 대신에 commPortIdentifier 클래스의 정적 메쏘드(static method) getPortIdentifier() 메쏘드를 사용하여 포트 식별자를 만들 수 있다.

public static Enumeration getPortIdentifier()

public static CommPortIdentifier getPortIdentifier(String portName)

        throws NoSuchPortException

public static CommPortIdentifier getPortIdentifier(CommPort port)

        throws NoSuchPortException

 이 중 가장 일반적인 메쏘드는 CommPortIdentifier.getPortIdentifier()이다. 이 메쏘드를 사용하여 시스템의 모든 포트 리스트를 저장하고 있는 java.util.Enumeration 객체를 리턴한다.

 사용 가능한 포트를 얻었으면 CommPortIdentifier 객체의 open() 메쏘드를 사용하여 포트를 열어야 한다.

public synchronized CommPort open(String appname, int timeout) 
                                  throws PortInUseException

  open() 메쏘드를 사용하여 포트를 열고 나서 CommPort 클래스를 상속(inheritance)받고 있는 SerialPort 클래스로 형변환(type casting)을 시키면 시리얼 포트를 열 수 있다.

SerialPort serialPort = (SerialPort) portId.open("SimpleSerialApp", 2000);

 또한 SerialPort 객체의 setSerialPortParam() 메쏘드를 사용하여 전송속도(Baud Rate), 데이터 비트(data bits), 스톱 비트(stop bits), 패리티(parity) 등을 설정할 수 있다.

시리얼 포트를 열고 나서 시리얼 포트에서 이벤트 리스너(event listener)를 사용하여 데이터가 수신되기 기다린다(Listen). 시리얼 포트에서 데이터가 수신되면 SerialPortEvent가 발생하고, 이 이벤트를 처리하기 위해서 SerialPortEventListener interface SerialEvent() 메쏘드에서 시리얼 통신에 대한 것들을 구현(implement)하면 된다. 이것은 java AWT Swing과 같은 GUI(Graphical User Interface) 프로그래밍에서의 이벤트 처리 방식과 동일하다.

 프로그램 2는 시리얼 포트에서 수신된 문자를 그대로 다시 전송하는 에코프로그램(echo program) 이다.

 

출처  http://blog.naver.com/wisdory/100012210954

'프로그래밍 > java' 카테고리의 다른 글

자바 애플리케이션에서 동적으로 PDF 파일 생성하기(한글 적용)  (0) 2009.07.02
javax.comm 이용시 Port를 못찾는 경우..  (0) 2009.06.26
jxl  (0) 2009.06.10
jxl 생성  (0) 2009.06.10
jxl 수정  (0) 2009.06.10