Establishing a Connection using javax.comm (commapi)

Hi all. I know how to claim com ports and then send data into them using the comm api. But I want to be able to establish a connection between 2 com ports (running the same program at both ends). I only want to send data into the port if i know the other end is listening. Also if the connection was broken I want to be able to warn the user. Does anyone know how i can implement this. Do i need to implement some sort of handshaking? Any code examples much appreciated.
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

ashok3sepConnect With a Mentor Commented:
SUN has come out with a new API for Communications.
It is available for download at the Java Developer Connection.
This package has sample code to read/write Communication ports.
This package should solve your problem.
import java.util.*;
import javax.comm.*;

public class SimpleWrite {
    static Enumeration portList;
    static CommPortIdentifier portId;
    static String messageString = "Hello, world!\n";
    static SerialPort serialPort;
    static OutputStream outputStream;

    public static void main(String[] args) {
        portList = CommPortIdentifier.getPortIdentifiers();

        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
             System.out.println("Port type: " + portId.getPortType());
             if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                System.out.println("Port name: " + portId.getName());
                if (portId.getName().equals("/dev/term/a")) {
                    try {
                            serialPort = (SerialPort)
                  "SimpleWriteApp", 2000);
                            System.out.println("COM port  " + portId.getPortType() + "opened");                          
                    } catch (PortInUseException e) {}
                    try {
                        outputStream = serialPort.getOutputStream();
                    } catch (IOException e) {}
                    try {
                    } catch (UnsupportedCommOperationException e) {}
                    System.out.println("Data bits set to 8");
                    System.out.println("Stop bits set to 1");
                    System.out.println("Parity set to NONE");
                    try {
                       System.out.println("Writing " + messageString);
                    } catch (IOException e) {}

Here in this example you open the output stream and then write the string to it

so simply calling Input stream and do the same procedure for read.


All Courses

From novice to tech pro — start learning today.