23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Java</strong> I/O<br />

By default, no events are fired when the serial port's state changes. If you pass true to any of<br />

these methods, the VM will fire a serial port event when the matching state changes. Example<br />

17.8 activates the Ring Indicator and prints a message on System.out when the modem tells<br />

the computer the phone is ringing.<br />

Example 17.8. PhoneListener<br />

import javax.comm.*;<br />

import java.util.TooManyListenersException;<br />

public class PhoneListener implements SerialPortEventListener {<br />

public static void main(String[] args) {<br />

String portName = "COM1";<br />

if (args.length > 0) portName = args[0];<br />

PhoneListener pl = new PhoneListener();<br />

try {<br />

CommPortIdentifier cpi =<br />

CommPortIdentifier.getPortIdentifier(portName);<br />

if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {<br />

SerialPort modem = (SerialPort) cpi.open("Phone Listener", 1000);<br />

modem.notifyOnRingIndicator(true);<br />

modem.addEventListener(pl);<br />

}<br />

}<br />

catch (NoSuchPortException e) {<br />

System.err.println("Usage: java PhoneListener port_name");<br />

}<br />

catch (TooManyListenersException e) {<br />

// shouldn't happen in this example<br />

}<br />

catch (PortInUseException e) {System.err.println(e);}<br />

}<br />

}<br />

public void serialEvent(SerialPortEvent evt) {<br />

}<br />

System.err.println(evt.getEventType());<br />

if (evt.getEventType() == SerialPortEvent.RI) {<br />

System.out.println("The phone is ringing");<br />

}<br />

17.5 Parallel Ports<br />

Parallel ports are most common on PCs. Sun SparcStations from the Sparc V on also have<br />

them. However, Macs do not have them, nor do many non-x86 workstations. Parallel ports are<br />

sometimes called printer ports, because their original purpose was to support printers. The<br />

names of the parallel ports—"LPT1," "LPT2," etc.—stand for "Line PrinTer," reflecting this<br />

usage. Nowadays, parallel ports are also used for Zip drives, tape drives, and various other<br />

devices. However, parallel ports are still largely limited by their original goal of providing<br />

simple printing. A parallel port sends data eight bits at a time on eight wires. These bits are<br />

sent at the same time in parallel, hence the name. The original parallel ports only allowed data<br />

to flow one way, from the PC to the printer. The printer could only respond by sending a few<br />

452

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!