Link to home
Start Free TrialLog in
Avatar of informvinay
informvinay

asked on

How to share a com port using java.

hi techies!
I'm making a application which would allow me share a single com port for two hardware devices which are sending messgaes to my pc,and i'm replying to both the devices.(communication is asynchronous type).so i need to send device specific messages.please help, can this be done using any java api.

pls help.
Avatar of heyhey_
heyhey_

have you tried JavaComm ?
Hi.....as heyhey said u can use comm api for that....it just works fine...

VasanS
ASKER CERTIFIED SOLUTION
Avatar of vijaywadnere
vijaywadnere
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of informvinay

ASKER

Hey Vijay
Can u please provide me a simple code.

Regards
Vinay
Well its not possible to put the code right here!!

why dont u send me an email and i'll send u a working code for COM port communication.

Infact, if anybody needs the code pls mail me at:

vijay2903@yahoo.com

best wishes.

...and, thanx for the points!! :)
vijaywadnere and informvinay,

I note that you're both relatively new members here, so I'm going to give you a break for what might seem like an innocuous event, but which in fact is a serious violation of the membership agreement.

In addition to being a site where you can get answers to questions fairly quickly, and assistance from top-notch experts in a wide range of fields, Experts Exchange is a repository for future users. By using email to communicate answers to questions outside of EE, you violate the Exchange of information. Such actions will not be tolerated, and future occurrences will result in points being removed from your accounts, and can lead to further actions by Administration.

vijaywadnere,

Please post the code here; I've seen some fairly sophisticated posts in other questions.

Thanks to both of you,

Netminder
CS Moderator

Netminder,i think its all cause we want to run before we can walk!!

InformVinay, here's the required code in Java. You'll need to plug your MODEM and keep it ON to run the program. Alt. you can use a NULL MODEM at your COM port.

Command Line:>> java Main COM1
(COM1 or COM2 depends on what port you are using)
(do not mind the GUI, i'm really bad at it)

If everything goes well, whatever typed at lefthand textfield, will be displayed in the righthand textarea.

*******************************************
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.comm.*;
import java.util.*;
public class Main extends Frame implements ActionListener {
        TextArea status;
        Thread recvThread;
        Receiver recv;
        Transmitter tran;
        CommPortIdentifier portId;
        CommPort cp;
        boolean okay, opened;
        Panel initP;
        Button initB, exit;
        public Main(String port) {
                super("My Serial Communicator");
                status = new TextArea();
                status.setEditable(false);
                add(status, "North");
                try {
                        portId = CommPortIdentifier.getPortIdentifier(port);
                        cp = portId.open("Main", 5000);
                        okay = true;
                        opened = true;
                } catch(NoSuchPortException e){
                        status.append("No Such Port: "+port+"\n");
                        okay = false;
                } catch(PortInUseException e) {
                        status.append("Port ["+port+"] in Use by ["+ portId.getCurrentOwner() +"]\n" );
                        okay = false;
                }
                setSize(800, 600);
                initP = new Panel();
                initB = new Button("Init");
                initB.addActionListener(this);
                initP.add(initB);
                add(initP, "Center");
                exit = new Button("Exit");
                exit.addActionListener(this);
                add(exit, "South");
                this.validate();
                setVisible(true);
        }
        protected void init() {
                if(okay) {
                        recv = new Receiver(this, cp);
                        recvThread = new Thread(recv);
                        tran = new Transmitter(this, cp);
                        add(tran, "West");
                        add(recv, "East");
                        recvThread.start();
                        remove(initP);
                        this.validate();
                }
        }
        public void actionPerformed(ActionEvent e) {
                if( e.getSource() == exit ) {
                        if(okay) {
                                //close the port;
                                recvThread = null;
                                try {
                                        opened = false;
                                        recv.close();
                                        tran.close();
                                        cp.close();
                                        System.out.println("Comm Port Closed.");
                                } catch(Exception ee) {
                                        System.out.println("Execption while closing port:");
                                        System.out.println(ee);
                                }
                        }
                        this.dispose();
                        System.exit(0);
                }
                if( e.getSource() == initB ) {
                        init();
                }
        }
        public static void main(String[] arg) {
                Main m = new Main( arg[0] );
        }
}
class Transmitter extends TextField implements ActionListener {
        Main owner;
        CommPort cp;
        boolean okay;
        OutputStream os;
        public Transmitter(Main o, CommPort c) {
                super(20);
                owner  = o;
                cp = c;
                try {
                        os = cp.getOutputStream();
                        okay = true;
                } catch(Exception e) {
                        okay = false;
                        owner.status.append(e+"\n");
                }
                addActionListener(this);
        }
        public void actionPerformed(ActionEvent e) {
                String str = getText();
                if(okay) {
                        if(str.length()>0) {
                                try {
                                        os.write( str.getBytes() );
                                        setText("");
                                } catch(Exception ee) {
                                        owner.status.append(ee+"\n");
                                }
                        }
                } else {
                        owner.status.append("Could Not Transmit\n");
                }
        }
        public void close() {
                owner = null;
                cp = null;
                if(okay) {
                        try {
                                os.close();
                                System.out.println("Output Stream Closed.");
                        } catch(Exception e) {
                                System.out.println("Exception while closing transmitter:");
                                System.out.println(e);
                        }
                }
        }
}
class Receiver extends TextArea implements Runnable {
        Main owner;
        CommPort cp;
        boolean okay;
        InputStream is;
        byte buffer[];
        public Receiver(Main o, CommPort c) {
                super();
                owner = o;
                cp = c;
                buffer = new byte[2048];
                setEditable(false);
                try {
                        is = cp.getInputStream();
                        okay = true;
                } catch(Exception e) {
                        okay = false;
                        owner.status.append(e+"\n");
                }
        }
        public void run() {
                while(owner.opened) {
                        System.out.print(".");
                        try {
                                while ( owner.opened && is.available()>0) {
                                        int bytes = is.read(buffer);
                                        System.out.print("~");
                                        if(bytes>0) {
                                                this.append( new String(buffer,0,bytes) + "\n");
                                        }
                                }
                        } catch(Exception e) {
                                owner.status.append(e+"\n");
                        }
                        try {
                                synchronized(this) {
                                        wait(500);
                                }
                        } catch(InterruptedException e) {}
                }
        }
        public void close() {
                owner = null;
                cp = null;
                if(okay) {
                        try {
                                is.close();
                                System.out.println("InputStream closed.");
                        } catch(Exception e) {
                                System.out.println("Exception while closing Receiver:");
                                System.out.println(e);
                        }
                }
        }
}
*******************************************
hi vijay!

i have been doing a class to send a string to com port, i read your example for read the port.. but i cant read ... the program say's no such port... i have a printer connected to a com1 port... i cant detect her... if you can help me.. i apreciate... thnks ;)
hi All,

I've received a mail similar to the question arised by r4yb.
I thought it would be beneficial for all if it is answered here.

the javacomm api contains 3 main things.
1. win32comm.DLL (must be in jdk1.3/bin folder)
2. javax.com.properties (must be in jdk1.3/lib folder)
3. comm.jar (should be in classpath)

now, to access/handle a hardware that is connected to a port, one should know the proper sequence to data/commands that is to be sent to the corresponding port. simply writing 'bytes' to a printer port will NOT actually print them on printer.

I've never seen a Printer attached on a COM port, it should be on a parallel port (LPT). though I never programmed a parallel port, but the same procedure may be applied and it should work if both the terminals (PC & Hardware attached at port) understands a common protocol.

in addition to it, one may paste his/her code over here, and we can try to make it work.

regards all,
- Vijay Wadnere
hi all,

thnks Vijay.

.:: Sory my bad English :/ ::.

i've realy a printer connected to a com port, i never see one like this.... it's very weird, it's a "Star SP300".

code :

****************
void jButton2_actionPerformed(ActionEvent e) {

  String port = "COM2";

  try {
 
    System.out.println("before port id");
    portId = CommPortIdentifier.getPortIdentifier(port);
    System.out.println("after port id");
    cp = portId.open("testeApp",5000);
    System.out.println(" cp : " + cp);
  } catch(NoSuchPortException np){
    System.out.println("No Such Port: "+port+"\n");
  } catch(PortInUseException up) {
    System.out.println("Port ["+port+"] in Use by ["+ portId.getCurrentOwner() +"]\n" );
  }

    System.out.println("get port identifiers : " + CommPortIdentifier.getPortIdentifiers());
    System.out.println("get port serial  : " + CommPortIdentifier.PORT_SERIAL);
    System.out.println("get port paralel : " + CommPortIdentifier.PORT_PARALLEL);

}

**************


In this part i only test the port.
the program passed for first "System.out" and after he detects an exception (NoSuchPortException).

I'm doing something wrong?

thnks