O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reading and Writing: Lock Step

Problem

You want to read and write on a port, and your communications needs are simple.

Solution

Just use read and write calls.

Discussion

Suppose you need to send a command to a device and get a response back, and then send another, and get another. This has been called a “lock-step” protocol, since both ends of the communication are locked into step with one another, like soldiers on parade. There is no requirement that both ends be able to write at the same time (see Recipes 10.7 and 10.8 for this), since you know what the response to your command should be and don’t proceed until you have received that response. A well-known example is using a standard Hayes-command-set modem to just dial a phone number. In its simplest form, you send the command string ATZ and expect the response OK, then send ATD with the number, and expect CONNECT. To implement this, we first subclass from CommPortOpen to add two functions, send and expect, which perform reasonably obvious functions for dealing with such devices. See Example 11-5.

Example 11-5. CommPortModem.java

import java.awt.*; import java.io.*; import javax.comm.*; import java.util.*; /** * Subclasses CommPortOpen and adds send/expect handling for dealing * with Hayes-type modems. * */ public class CommPortModem extends CommPortOpen { /** The last line read from the serial port. */ protected String response; /** A flag to control debugging output. */ protected boolean debug = true; public CommPortModem(Frame ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required