BUY THIS BOOK
Add to Cart

Print Book $39.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £28.50

What is this?

Looking to Reprint this content?


Palm OS Network Programming
Palm OS Network Programming Writing Connected Applications for the Palm

By Greg Winton
Price: $39.95 USD
£28.50 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Connected Palms
"You mean you can connect these Palm things?" is the second question most people ask me when I tell them that I'm writing a book on Palm OS network programming. The first is, "I'm sorry, what is your book about?"
This book is for software developers who are comfortable with the basics of Palm OS programming and are interested in developing networking applications for the platform.
The past five years have seen incredible growth in both the Personal Digital Assistant (PDA) market in general, and the Palm OS Platform in particular. While any book on Palm OS programming is unlikely to appear in Oprah's Book Club, the Palm V did appear as a Christmas Gift pick, almost two years ago.
At the beginning of 1999, there were seven Palm OS-based devices from Palm (at that time a division of 3Com), IBM, and Symbol Technologies. Today there are dozens of devices from Handspring, Sony, TRG, and many others, as well as a stream of new devices from Palm, IBM, and Symbol. These devices have rapidly expanded into the consumer, professional, and enterprise markets. And these markets still remain relatively untapped.
Wireless networking technologies are maturing. Local Area Wireless Networks (LAWNs) that cover an office or building are becoming more common in mainstream applications. The Personal Area Wireless Network (PAWN) technologies, of which Bluetooth is the most famous, are maturing rapidly.
Mobile phone and PDA technologies are converging. Qualcomm's pdQ married a Palm OS device with a mobile phone. It never quite found its niche, but it was a foreshadowing of the latest gadgets. Handspring sells a Springboard device that turns your Visor into a mobile phone. Each vendor provides an expansion port for its device; we can expect many interesting combinations in the future.
The rise of peer-to-peer networking provides an excellent opportunity for network-enabled handheld computers. Peer networking applications act as both clients and servers, tapping into a web of peers for support. Desktop-based peer-to-peer applications allowing users to share music, pictures, and ideas have exploded into the marketplace and public consciousness. These applications reveal a deep-seated desire for people to communicate.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Brief History of Palm OS Networking
Palm OS Networking has come a long way in the five years since the first device was released. As the platform has evolved, networking support has evolved as well. But not as fast.
In the beginning, there was the Pilot 1000. This was a lean machine with 128K of dynamic memory. It had everything it needed for the built-in applications and no more. It was soon followed by the Pilot 5000. The dynamic memory was increased to 512K, but this increase went straight to the storage heap.
Third party applications and hacks began to appear. The applications were of more interest than use. The hacks were useful, smoothing out the rough edges of the young operating system.
The design goals for these early devices were simple. The device had to be small enough and light enough to fit in a shirt pocket. And it had to survive on two AA batteries for at least three weeks at a time. None of these devices supported networking; their only link to the outside world was through the HotSync.
The introduction of the PalmPilot in 1997 opened the door to network connectivity. The standard PalmPilot came with 512K, but the Professional model had 1 MB, just enough for a protocol stack. The new operating system introduced networking support. The Net Library (a.k.a. NetLib) provided the developer with access to this protocol stack.
We discuss the Net Library in Part II of this Book.
Network support was added primarily to enable network HotSync. This allowed users to synchronize remotely with their desktops. Palm then introduced a wired modem to provide dial-up connectivity. Loading the protocol stack consumed most of the available dynamic memory, but a careful developer could shoehorn a network application into the few remaining resources. Not many did, but it was a start.
The Palm III, introduced in 1998, was a huge step forward in Palm networking, even though it added little to the available networking support. Billed as "The Connected Organizer," the new device came with 2 MB of dynamic RAM. Even after loading the protocol stack, there were still enough resources left for networking applications.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Networking Options
Just as there are a wide variety of Palm devices, there are a wide variety of networking options. Each of these options has their strengths and weaknesses. The key to selecting the proper networking option is to make sure it fits the needs of your application. But whatever your network connection, a Net Library-based application should work unchanged.
The dial-up architecture hasn't changed since the first wired modems were introduced for the PalmPilot. The modem connects the Palm to the telephone network, translating data traffic to and from sounds. Figure 1-1 shows the dial-up networking architecture.
Figure 1-1: Dial-up networking architecture
Dial-up networking provides a simple connection to corporate or public data. The Palm must be configured to access the network through a remote access server (RAS) or Internet service provider (ISP). This is simpler than on a desktop, as there are no drivers to configure and few available options.
The user can connect to the network from any phone jack, but the downside is that the user is tied to this phone jack for the duration of the network session. This solution is best for regular, but not overly frequent updates of information.
The basic architecture for wireless modems is ` similar to wired modems. Instead of using the phone network to access the Internet, wireless modems connect over a wireless network. Figure 1-2 shows the architecture for general-purpose (as opposed to Palm VII) wireless connectivity.
Figure 1-2: Wireless networking architecture
In the wireless model, the device is attached to a wireless modem. This modem exchanges data with the nearest radio tower. This tower is in turn connected to an Internet gateway.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
From the simple concept of a personal organizer, optimized to fit in a shirt pocket and live on AA batteries, the Palm OS has come a long way since the first device was released. While still the most battery-efficient device on the market, battery life has been traded for color, size, and network connectivity. Even size and simplicity lose to network connectivity.
There are lots of choices for connecting to the network. Wireless is the most well suited for the Palm's form factor and design philosophy (discussed in Chapter 3). Narrowband wireless provides Internet connectivity from anywhere, or at least from anywhere there is coverage, via the wireless networks. RF networks provide broadband Local Area Wireless Network (LAWN) connectivity, but only within certain areas.
The confluence of the handheld revolution and broadband wireless connectivity will generate a great demand for Palm OS network applications. This book prepares you for the flood.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: The Network Application Model
One of the principal tenets of the Zen of Palm is that a solution should anticipate the needs of the majority of its users. The Palm protocol stack certainly meets this criteria—it is TCP/IP-based. TCP/IP is the lingua franca of the Internet; the majority of applications will use TCP/IP or its sibling in the Internet Protocol Suite, UDP/IP.
A network programming interface allows the application to access the protocol stack in a transport and network independent fashion. The Palm OS provides a reasonable subset of the Berkeley Sockets interface, the de facto standard network programming interface. The Net Library's interface has not changed since its introduction four years ago. In this chapter, we introduce the Open System Interconnect (OSI) model, the ISO standard for network protocol stacks, and the Berkeley Sockets API, which is the de facto standard programming interface to network services. We examine how these models have been applied on the Palm OS platform.
The International Organization for Standardization (ISO) defines technical and mechanical standards for the industry. ISO is a worldwide federation of national standards organizations from 130 countries. The American National Standards Institute (ANSI) defines these standards in the U.S. and is a member of ISO.
ISO is not an acronym for International Organization for Standards, or anything else. It is derived from the Greek word iso, meaning equal.
ISO produces standards for everything—from country and language names to smart card dimensions; from quality assurance processes to screw thread dimensions. Among these many standards is the Open Systems Interconnect (OSI) standard for computer connections. The OSI standard provides a proven architecture for network-enabled devices and applications to follow, allowing different hosts to communicate across a network.
According to the OSI model, there are seven distinct layers in a network application. Each layer provides one or more protocols that build an abstraction on the layer below it, shown in Figure 2-1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The OSI Model
The International Organization for Standardization (ISO) defines technical and mechanical standards for the industry. ISO is a worldwide federation of national standards organizations from 130 countries. The American National Standards Institute (ANSI) defines these standards in the U.S. and is a member of ISO.
ISO is not an acronym for International Organization for Standards, or anything else. It is derived from the Greek word iso, meaning equal.
ISO produces standards for everything—from country and language names to smart card dimensions; from quality assurance processes to screw thread dimensions. Among these many standards is the Open Systems Interconnect (OSI) standard for computer connections. The OSI standard provides a proven architecture for network-enabled devices and applications to follow, allowing different hosts to communicate across a network.
According to the OSI model, there are seven distinct layers in a network application. Each layer provides one or more protocols that build an abstraction on the layer below it, shown in Figure 2-1.
Figure 2-1: The OSI reference model
The top three layers are provided by the application; the lower four are provided by the operating system. We refer to the layers implemented by the application as the application protocol stack. The layers provided by the operating system are the network protocol stack.
A protocol is a set of rules that allows two hosts to communicate without prior knowledge of each other. Any set of rules that allow communication can be considered a protocol. For example, human languages are protocols that allow individuals to communicate.
The application protocol stack implements domain-specific behavior and protocols. For example, the application protocol stack for an FTP client allows the user to browse a file server and download files from that server. If the user has sufficient access rights, they can upload files to the server as well. The client application translates the user's requests into the appropriate FTP commands, which it sends to the server. The application protocol stack may encrypt this data or compress it, but it does not get involved in the actual transmission of the data.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
OSI Layers
The OSI model outlines seven layers: application, presentation, session, transport, network, data link, and physical. The first three layers define and implement domain-specific exchanges between hosts. The last four layers provide for the more-or-less reliable end-to-end transmission between the local process and a remote.
Application protocols allow the network application to exchange domain-specific data with a network application running on a remote host. For a file transfer application, the domain-specific data is the files and their properties. In a daytime application, the domain-specific data is the current date and time.
An application protocol is a pre-agreed syntax of commands and responses that allow the two processes to exchange this domain-specific data. Our file transfer application uses the File Transfer Protocol (FTP), which was defined in RFC 959. The daytime application uses the Daytime Protocol (DTP), which is defined in RFC 867. Both protocols date back to the ARPA days of the Internet.
The application layer is also responsible for providing an interface to external systems, such as users. The application translates user input into application data, which is sent to the remote application according to the rules of the application protocol. When the user selects the "login" button, our file transfer application prompts the user for the server name, username, and password. It then translates this application data into an FTP login operation. It presents the server's response to this login to the user, if only in the form of new buttons appearing and old ones disappearing.
Most application protocols are based on request and response. In the request and response model, there are consumers and suppliers. Consumers request services, suppliers provide them. A consumer sends a request to the supplier. The supplier processes the request and provides the service. Figure 2-5 illustrates the request and response protocol model.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
The OSI model provides a template for designing and implementing network applications and network protocol stacks. The application translates user input and other events into network operations, and handles the results. The network application developer develops the application to handle a specific problem—for example, file transfer, electronic mail, or messaging.
Network operations are executed by the network protocol stack. The network protocol stack handles are required for more-or-less reliable end-to-end data transfer between network hosts. The Palm OS provides a network protocol stack. This protocol stack runs as its own task, independent from the applications that use it.
The network application programming interface (API) provides intertask communication between the application and network protocol stack. The Palm networking API, Net Library, is based loosely on the Berkeley Sockets interface, the de facto networking API standard. The Net Library hides the complexity of intertask communications and network access behind an easy-to-use, flexible C API.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Designing Network Applications
The Palm platform is a resource-starved device running an underpowered processor. Its limitations have not changed much over the years. The challenge for Palm application developers is to make efficient use of these scarce resources and weak processor to provide an intuitive and pleasant user experience. The Zen of Palm addresses this challenge by preaching the virtues of simplicity.
Adding network connectivity to a Palm application deepens this challenge. Networks, especially wireless ones, often suffer from narrow bandwidth and high latency. Accessing network resources tends to be slow, unreliable, and complex, relative to local resources. Continuing in the pseudo-Buddhist paradigm, the Tao of Networks is a set of considerations for network application development that allow applications to make efficient use of inefficient networks.
This chapter is about designing successful Palm network applications. We explore the Zen of Palm and the Tao of Networks, then create a high level design for our two example applications, FtpView and Daytime Peer.
The original Palm engineers envisioned a Personal Information Management (PIM) device small and lightweight enough to fit comfortably in a shirt pocket and efficient enough to run on conventional batteries. They succeeded. The Pilot 1000 could run for weeks on two AA batteries and was about the size and weight of a deck of cards.
It was the perfect personal information management tool. It was smaller and more flexible than a paper-based system. It could go with you to meetings, unlike a computer-based system, and it was cheap enough to fit on an expense account. It was a handheld device middle management could appreciate, and a big hit in corporate America.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Zen of Palm
The original Palm engineers envisioned a Personal Information Management (PIM) device small and lightweight enough to fit comfortably in a shirt pocket and efficient enough to run on conventional batteries. They succeeded. The Pilot 1000 could run for weeks on two AA batteries and was about the size and weight of a deck of cards.
It was the perfect personal information management tool. It was smaller and more flexible than a paper-based system. It could go with you to meetings, unlike a computer-based system, and it was cheap enough to fit on an expense account. It was a handheld device middle management could appreciate, and a big hit in corporate America.
The manageable size, the extended battery life, the low-powered screen and processor, and the simple intuitive interface all contributed to the Palm's appeal as an information appliance. It seemed less like a computer and more like a smart date book.
The economies that allowed the original devices to run so long and be so small were applied to the operating system and built-in applications as well. The Zen of Palm is shorthand for the less-is-more philosophy that guided the original Palm engineers. As the device evolved into a more general computing platform, third-party applications appeared and were fruitful and multiplied. Developers were encouraged to apply the "less is more" approach to their applications.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Designing FtpView
FtpView is a limited FTP client application created in this book, which provides only enough functionality to demonstrate the usage of TCP sockets. We demonstrate establishing and accepting connections and exchanging data over these connections. FtpView illustrates these techniques by supporting login to an FTP server, listing the server's current directory, and logging out from the server.
FtpView provides moderate, read-only access to FTP servers. We develop this application in Chapter 6 through Chapter 12. When complete, FtpView will allow the user to log in to and out from the FTP server, and retrieve the listing of files in the server's root directory. Figure 3-1 shows the application flow for FtpView.
Figure 3-1: FtpView application flow
When the user starts the application, the only available option is to begin an FTP session. Once the session has begun, the user can list the server directory contents or log out. The user can list the server directory as often as they like during the session, but when the user logs out from the FTP server, the session is ended and she is back where she started. The user must begin a new session by logging in to an FTP server again before she can list the server files or log out again. We will examine in turn each of the following FTP operations: login, list, and logout.

Section 3.2.1.1: Login

The user starts an FTP session by selecting the Login command. This begins the FTP login process, which is illustrated in Figure 3-2.
Figure 3-2:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Designing Daytime Peer
FtpView demonstrates general networking concepts such as connecting to the network and host resolution, as well as exploring TCP connections in depth. The other major Internet transport protocol is the User Datagram Protocol, or UDP. UDP is a lighter-weight, less reliable protocol than TCP.
We will explore the User Datagram Protocol with Daytime Peer, a Daytime Protocol peer application. The Daytime Protocol allows hosts to request the current date and time service from other hosts. We refer to the host that requests the service as the consumers and the host that provides the service as the supplier. Daytime Peer acts as both consumer and supplier. In the default configuration, it consumes the same time service that it supplies.
Daytime Peer is a much simpler application than FtpView, even though we provide both a consumer and a supplier component. At program startup, the application is configured to communicate with itself, mostly for purposes of illustration. The user is free to select a different time server and receive the time from it. We will examine the Daytime consumer and supplier separately.

Section 3.3.1.1: Daytime consumer

A Daytime consumer sends requests for the Daytime service to Daytime suppliers, and receives the supplier's response. Figure 3-8 illustrates the application flow of the Daytime Peer consumer.
Figure 3-8: Daytime consumer application flow
The user begins a Daytime session by selecting start. The peer "connects" the socket to the remote address. UDP is a connectionless protocol; this connection is not required and is not a connection in a networking sense. It simply means that the socket will send to the same remote address on every send operation, unless another address is specified in the send operation.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Implementation Plan
We implement our applications slowly, examining each new operation as it is added. In Chapter 6 and Chapter 7, we execute the basics required for most network applications: connecting to the network and host resolution. In Chapter 8 through Chapter 12, we implement FtpView as we explore TCP connections. In Chapter 13, we carry out the complete Daytime Peer. This simple application illustrates UDP-based applications. The implementation schedule for our applications is listed in Table 3-1.
Table 3-1: Example applications implementation schedule
Chapter
Description
6
Base: open and close network connection
7
Base: resolve hosts and services
8
FtpView: connect to sockets
9
FtpView: exchange data with FTP server (scripted)
10
FtpView: exchange data with FTP server (event-driven)
11
FtpView: listen for and accept connection requests
12
FtpView: use nonblocking Sockets
13
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
On a handheld device where you are trying to minimize production costs and maximize battery life, you can't afford to throw away processor cycles or resources. Network access brings its own challenges. As a rule, it is slow, unreliable, and complex. Fortunately, there are guidelines to create enlightened Palm Network applications. A Palm Network application should:
  • Be self-explanatory
  • Provide only the essential forms and features
  • Be safe to explore
  • Avoid user input wherever possible and provide assistance where user input cannot be avoided
  • Walk lightly on the platform
  • Avoid the network insofar as it is possible
  • Minimize network traffic
  • Yield to others
  • Closely monitor network operations
  • Never leave its partners hanging
It is not only a matter of responsiveness, although as resources are consumed and cycles wasted, responsiveness will suffer too. It's a matter of working well on the application platform.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Development Tools
There are many different development tools that allow you to write Palm applications, ranging from 68K assemblers to sophisticated forms packages. There are several flavors of Basic and a growing number of Java virtual machines. Still, most applications, including the examples in this book, are written in C or C++.
There are two C/C++ development environments: Metrowerks CodeWarrior and the Free Software Foundation's PRC tools. CodeWarrior is available for Mac OS and Windows; the PRC tools are supported on Windows and Linux. Both toolsets include resource compilers and source-level debuggers. The Palm OS Emulator is a crucial tool in the development of Palm OS applications in general, and Palm OS network applications in particular. Mochasoft's MochaPPP is useful for testing Palm OS network applications, though not the ones in this book, ironically. This chapter discusses these tools in depth.
The tools for developing network applications are the same as for developing standalone applications. This book assumes that the developer is familiar with the basics of developing Palm OS applications with either the CodeWarrior or PRC tools, and debugging these applications with the Palm OS Emulator. If not, Neil Rhodes and Julie McKeehan's excellent book, Palm Programming: The Developer's Guide (O'Reilly & Associates), provides a superior introduction to these and other Palm OS development issues.
The original Palm operating system was developed on the Macintosh using Metrowerks CodeWarrior; this was the only development environment for the Pilot 1000. Since then, CodeWarrior has been ported to Windows, and, after several releases, the Windows version has achieved the stability and usability that Macintosh developers have long enjoyed.
CodeWarrior is the tool of choice for most commercial Palm OS application developers, and is the "official" development environment. This commercial arena allows you to create C and C++ Palm applications, shared libraries, and code resources on either the Windows or Macintosh platforms. It provides an Integrated Development Environment (IDE), in which you can edit your code, create user interface resources, compile and link the project, and debug the application directly on the Palm OS Emulator (POSE). We discuss POSE later in this chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Development Tools
The tools for developing network applications are the same as for developing standalone applications. This book assumes that the developer is familiar with the basics of developing Palm OS applications with either the CodeWarrior or PRC tools, and debugging these applications with the Palm OS Emulator. If not, Neil Rhodes and Julie McKeehan's excellent book, Palm Programming: The Developer's Guide (O'Reilly & Associates), provides a superior introduction to these and other Palm OS development issues.
The original Palm operating system was developed on the Macintosh using Metrowerks CodeWarrior; this was the only development environment for the Pilot 1000. Since then, CodeWarrior has been ported to Windows, and, after several releases, the Windows version has achieved the stability and usability that Macintosh developers have long enjoyed.
CodeWarrior is the tool of choice for most commercial Palm OS application developers, and is the "official" development environment. This commercial arena allows you to create C and C++ Palm applications, shared libraries, and code resources on either the Windows or Macintosh platforms. It provides an Integrated Development Environment (IDE), in which you can edit your code, create user interface resources, compile and link the project, and debug the application directly on the Palm OS Emulator (POSE). We discuss POSE later in this chapter.
CodeWarrior's straightforward installation process, graphical user interface, and integration with POSE eases the development of Palm applications, especially for developers uncomfortable with makefiles, command-line interfaces, and the Unix flavor of the PRC tools.
Before CodeWarrior was ported from the Macintosh to Windows, there was no way to develop for the Palm platform on Windows or Unix. Volunteer programmers leveraged the Free Software Foundations GNU `C' Compiler (GCC) to create the GNU PalmPilot SDK, which allows Palm application development on these desktop platforms. This toolset is now known as PRC Tools and is maintained, in part, by resources from Palm, Inc.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Debugging Tools
Developing Palm OS network applications is hardly different from standalone applications. Debugging network applications is a different story. The majority of standalone applications can be debugged directly on the device using either the CodeWarrior or PRC tools debugger. The debugger uses the Palm Serial Link protocol to communicate with the device over the serial port. Network applications need the same serial port to access the network.
Fortunately there are solutions that allow you to debug and test your network application. The Palm OS Emulator (POSE) provides a virtual device that runs on a desktop and allows developers using either CodeWarrior or PRC tools to debug their network applications at the source level. Mochasoft's MochaPPP simplifies testing by letting the device share the host desktop's network protocol stack. We will discuss each of these tools in turn.
POSE emulates a Palm device at the hardware level. In fact, it emulates a wide range of Palm and Palm-compatible devices, using images of the actual device ROMs. POSE enables source-level debugging of all Palm applications, especially network ones.
Palm, Inc. provides versions of the Palm OS Emulator for Windows and Mac OS; it has also been ported to Linux. This tool is available on both the Windows and Macintosh platforms. The source code is available for Unix developers; they must build the tool themselves. POSE can be used with either CodeWarrior or the PRC tools. You should be sure to use either the most recent version, or the second-most recent version. At the time of this writing, the current version is 3.2. POSE is available for download from the Palm OS web site at http://www.palmos.com/dev/tech/tools.
It's a good idea to wait until the newest version of POSE has been out for a few months before using it to test your code in case something really important breaks. This is our policy for all debugging tools, and we never change any tools once a project enters Beta testing.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
There are two environments for developing Palm OS Applications in C/C++. Metrowerks CodeWarrior for Palm OS is the "official" development environment, used by the vast majority commercial developers. Its graphical IDE eases managing project files, creating resources, building targets, and debugging. Its lack of a command-line interface limits the capacity for automatic build scripts or easily generating multiple targets.
PRC tools is an open source package based on the Free Software Foundation's GNU C/C++ compiler. This toolset suffers from the issues generally found in open source projects: lack of support and anarchic development and unpredictable releases. Although Palm has contributed resources to maintaining and extending these tools, and some of the most talented developers in the Palm community are dedicated to expanding their capabilities, it is still problematic.
Debugging Palm OS Networking applications is a challenge. The best solution is to use the Palm OS Emulator (POSE), configured to use the host computers modem for a dial-up connection. Alternatively, the developer can redirect Net library calls to use the host's protocol stack, but this introduces several problems. MochaSoft's MochaPPP allows the developer to connect an actual device to the network, using the host as a PPP server and router.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: A Brief Tour of the Net Library
There are two layers to the Net Library: the network protocol stack and the application programming interface. The protocol stack is on the bottom, handling the nitty gritty details of network services. The programming interface sits on top, providing a way for your application to take advantage of these services. This architecture, and the details of its implementation, are the result of years of research and development on a wide variety of platforms. As a developer, you benefit from all this work. Understanding this work and the reasons behind the design decisions will help you write more efficient and stable network code.
In this chapter, we explore the Net Library from a distance. Don't worry, we dive into the details of Palm Network Programming in Chapter 6. If you're already an expert (or just really impatient), feel free to jump on ahead. We'll catch up. But if you persevere through this chapter, you'll be rewarded with a view of the architectural and functional beauty of the Net Library.
The Net Library provides networking services for the Palm OS. The standard implementation supports TCP and UDP over an IP network. In this section, we explore the architecture and design of the external interface presented to the networking applications, as well as the internal system that provides the networking functionality.
The Network Library can be divided into two parts: the API and the protocol stack. The API is the set of functions that an application invokes to access the Net Library's functionality. The protocol stack handles all communication with the network: connecting, sending, and receiving. These components are connected by a mailbox queue. Figure 5-1 illustrates these relationships.
Figure 5-1: Net Library architecture
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Design of the Net Library
The Net Library provides networking services for the Palm OS. The standard implementation supports TCP and UDP over an IP network. In this section, we explore the architecture and design of the external interface presented to the networking applications, as well as the internal system that provides the networking functionality.
The Network Library can be divided into two parts: the API and the protocol stack. The API is the set of functions that an application invokes to access the Net Library's functionality. The protocol stack handles all communication with the network: connecting, sending, and receiving. These components are connected by a mailbox queue. Figure 5-1 illustrates these relationships.
Figure 5-1: Net Library architecture
In this diagram, we see the client application invoking functions in the API. The API translates these into requests that are placed into the mailbox queue. The protocol stack reads the requests and talks to the network. The protocol stack then places a response into the mailbox queue. The API reads the mailbox queue and returns a result to the client application.
This is a fairly standard division of labor in network architectures. Mapped against the OSI network model, the protocol stack provides transport, network, and data link services. TCP and UDP are transport-layer protocols, IP is a network-layer protocol, and PPP and SLIP are data link-layer protocols. Your application needs to provide the application, presentation, and session services of the OSI model.
The Net Library API provides the interface between these layers. This is the same role that is played by the Berkeley sockets API on Unix platforms and the Winsock API on Microsoft Windows platforms. The mailbox queue is an operating system construct that allows the user interface task, under which the API is running, to communicate with the protocol stack's task.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using the Net Library
This is all very well and good, but what does the application do in this wonderful world of the Net Library? Let's take a look.
Before we dive into the functions themselves, let's talk briefly about system libraries. When your compiler comes to normal function calls, it embeds the symbolic function name into your code. Then the linker comes along and resolves this symbolic name to the actual address of the function's implementation. If the linker can't find the implementation of the function, then it generates a linker error.
Palm OS System Libraries work differently. They operate according to something known as the 68K Trap Dispatch mechanism. 68K refers to the series of processors from Motorola that run the Palm, the MAC, and a bunch of other devices. What we care about, though, is the Trap Dispatch Mechanism. When your compiler comes across a call to a function in a system library, instead of inserting a symbolic name, it puts in assembly instructions that generate an exception that is caught by the Palm OS's system trap dispatcher. The system trap dispatcher uses the first parameter to select the correct system library to invoke a function from. As a result, every call to the NetLib API takes a reference number as its first parameter (well, actually there are a few byte-ordering functions that don't, but they turn out to be macros).
The very first thing you must do is to find the Net Library. This is a three-step process. First, ask the operating system for its version. The Net Library appeared for the first time with the PalmPilot Professional, and it simply cannot be used on any device that is not running Palm OS Version 2 or above. The version of the OS is stored in the sysFtrNumROMVersion feature. If you don't know how to retrieve features, don't panic. We describe this in Chapter 6, when we discuss how to load, initialize, and open the Net Library.
Once you determine that you're running the right OS, you need to check if the Net Library is in fact there. Remember, system libraries such as the Net Library are not required for a Palm Device. Even though it has been included with every device since the PalmPilot Professional, there are no guarantees that it will always be available. The easiest way to check if the Net Library is installed is to try to get its version number. The version of the Net Library is stored in the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
Using the Net Library is fairly straightforward. You must, of course, find the library and load the protocol stack. Once the protocol stack is loaded, you can connect to a remote host, then send data to and receive data from that host. When you are done exchanging data, close down the connection. When you are finished with all network access, close the library and unload the protocol stack. The devil, as they say, is in the details. We face this devil over the next several chapters, as we build a sample application based on the File Transfer Protocol (FTP).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: Hello, NetLib
Before we dive into the nuts and bolts of network programming, let's make sure that the basic plumbing is in place. In this chapter, we cover the mechanics of initializing, opening and closing the Net Library, and the protocol stack. We examine the resources required by the protocol stack across the various versions of the Palm OS, and we also connect to the network.
The first step to using the Net Library is to initialize it. This is a fairly simple process. First, determine whether the Net Library is installed and, if so, which version is installed. Then locate the Library and save a reference to it. This reference will be passed to all subsequent function calls. Once you've done this, you're ready to hit the network.
Protocol stacks do an awful lot of work building and addressing packets, and as we will see, they use a lot of memory to do it. The Palm engineers knew that the Net Library was going to take up a lot of resources. They also knew that they couldn't know what size and shape Palm OS devices might take in the future. They imagined that a device might come along which not only did not need network access, but also could not afford the resources required to support network access.
So it is possible that your network application might find itself running on a device with no network support. And, being the professionally-minded sort of person who would buy this book, you will want to make sure that if your network application finds itself in such circumstances, it will be able to handle itself in a manner that does you proud.
Even if your network application finds network support on the device, it probably should check to make sure it is the right sort of network support. Old devices never really go away, they just get given to relatives. Code defensively! Check for the existence and version of the Net Library to make sure your network application will survive and thrive on, or at least make a graceful exit from, the device on which it is running.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Initializing the Net Library
The first step to using the Net Library is to initialize it. This is a fairly simple process. First, determine whether the Net Library is installed and, if so, which version is installed. Then locate the Library and save a reference to it. This reference will be passed to all subsequent function calls. Once you've done this, you're ready to hit the network.
Protocol stacks do an awful lot of work building and addressing packets, and as we will see, they use a lot of memory to do it. The Palm engineers knew that the Net Library was going to take up a lot of resources. They also knew that they couldn't know what size and shape Palm OS devices might take in the future. They imagined that a device might come along which not only did not need network access, but also could not afford the resources required to support network access.
So it is possible that your network application might find itself running on a device with no network support. And, being the professionally-minded sort of person who would buy this book, you will want to make sure that if your network application finds itself in such circumstances, it will be able to handle itself in a manner that does you proud.
Even if your network application finds network support on the device, it probably should check to make sure it is the right sort of network support. Old devices never really go away, they just get given to relatives. Code defensively! Check for the existence and version of the Net Library to make sure your network application will survive and thrive on, or at least make a graceful exit from, the device on which it is running.
The Palm engineers provided a method for determining which features are available on a given device. A feature is a 32-bit value that may be accessed by any application on a device. Features are identified by the application that owns them and by the number of the feature assigned by that application. The contents and meaning of a specific feature are defined by the application; the user of the feature must have
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Connecting to the Network
Now that you have a reference to the Net Library, you can start calling Net Library functions. Generally your application will assume that any required configuration has already been done via the Network Panel of the Preferences application. But if you have to make any changes to the configuration, you must do them before connecting to the network.
Before you can access the network, you must first open the Net Library. Call NetLibOpen to load and initialize the protocol stack:
Err NetLibOpen (UInt16 netLibRefNum, UInt16* ifErrsP);
The first parameter is, of course, the reference number. If any network interfaces fail to load, an error is stored in *ifErrsP.
NetLibOpen reads the network configuration information from the preferences database. It then loads and initializes the appropriate components of the network protocol stack. Any changes to the configuration made after NetLibOpen has been called have no effect until the protocol stack, or the specific interface to which the setting pertains, is shut down and loaded again.
NetLibOpen also creates a new task on the operating system for the protocol stack to run on, and initializes the mailbox queues that allow this task to communicate with the user interface task.
The protocol stack may include a network interface that uses a dial-up connection for network connectivity, such as the Point-to-Point Protocol (PPP) or the Serial Line Internet Protocol (SLIP). These drivers are loaded from the task that NetLibOpen is called on. The drivers may display a dialog to show the progress of establishing a connection to the server. NetLibOpen must therefore be called from the user interface task.
It is possible that one or more of the network interfaces may fail to load; for example, the modem may be unable to connect to a server. This does not cause
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Disconnecting from the Network
Once you have finished opening the Net Library, you can begin connecting, sending, and receiving on the network. I cover how to do that in great detail in the next chapters. Right now, I discuss what to do when you're done; i.e., close down the protocol stack.
Disconnecting from the network is easy—simply call NetLibClose:
Err NetLibClose (UInt netLibRefNum, Boolean immediate);
The immediate parameter indicates whether you want the Net Library to close immediately. This controls how the library is closed down. If this parameter is true, the protocol stack closes down as soon as it receives the request from the mailbox queue. If this parameter is set to false, the protocol stack starts a countdown to allow other applications, or even your same application, the opportunity to call NetLibOpen. If this occurs before the countdown reaches 0, the close is aborted and the protocol stack is not unloaded. This saves the user from the pain of waiting while connections are made and the protocol stack loads.
On the one hand, the Zen of Palm urges you to minimize resource consumption, so you'll want to shut down the protocol stack as soon as possible to free all those resources it uses. On the other hand, the Tao of Networking urges you to provide the most responsive experienc