Karim Harazin
Karim Harazin

Reputation: 1473

monitor serial port that already open with java

i am working on monitoring com port and get data as it is available, the port is being used by another program so is it possible to monitor the port without opening it This is the code

package comtest;

import javax.comm.*;
import java.io.*;

public class PortTyper {

    public static void main(String[] args) {

        try {
            CommPortIdentifier com =
                    CommPortIdentifier.getPortIdentifier("COM2");

            CommPort thePort = com.open("port", 10);

            CopyThread output = new CopyThread(thePort.getInputStream(),
                    System.out);

            output.start();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

class CopyThread extends Thread {

    InputStream theInput;
    OutputStream theOutput;


    CopyThread(InputStream in, OutputStream out) {
        theInput = in;
        theOutput = out;
    }

    @Override
    public void run() {

        try {
            byte[] buffer = new byte[256];
            while (true) {
                int bytesRead = theInput.read(buffer);
                if (bytesRead == -1) {
                    break;
                }
                theOutput.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}

so can i just see what the data come to the COM2 without

CommPort thePort = com.open("port", 10);

Thanks

Upvotes: 2

Views: 1880

Answers (2)

Bluesagar
Bluesagar

Reputation: 11

You can manually try monitoring the serial port using softwares like PortMon.

However this software is only available till Windows NT.

Upvotes: -1

raphui
raphui

Reputation: 117

You can't monitor the serial port if it is opened by another program because a serial port can't be opened 2 times simultaneously.

Upvotes: 2

Related Questions