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 EnumerationgetPortIdentifier()

public static CommPortIdentifiergetPortIdentifier(String portName)

       throws NoSuchPortException

public static CommPortIdentifiergetPortIdentifier(CommPort port)

       throws NoSuchPortException

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

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

public synchronized CommPortopen(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 interfaceSerialEvent()메쏘드에서 시리얼 통신에 대한 것들을 구현(implement)하면 된다.이것은javaAWTSwing과 같은GUI(Graphical User Interface)프로그래밍에서의 이벤트 처리 방식과 동일하다.

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


Posted by 영웅기삼
,