Tải bản đầy đủ (.pdf) (577 trang)

delphi - the tomes of delphi - basic 32-bit communications programming

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.03 MB, 577 trang )

TEAMFLY






















































Team-Fly
®

The Tomes of Delphi:
Basic 32-Bit Communications
Programming
Alan C. Moore

and
John C. Penman
Wordware Publishing, Inc.
Library of Congress Cataloging-in-Publication Data
Moore, Alan C., 1943
The Tomes of Delphi : basic 32-bit communications programming / by Alan C. Moore
and John C. Penman.
p. cm.
Includes bibliographical references and index.
ISBN 1-55622-752-3 (paperback)
1. Computer software—Development. 2. Delphi (Computer file). 3. Telecommunication
systems. I. Penman, John C. II. Title.
QA76.76.D47 M665 2002
005.1 dc21 2002011
CIP
© 2003, Wordware Publishing, Inc.
All Rights Reserved
2320 Los Rios Boulevard
Plano, Texas 75074
No part of this book may be reproduced in any form or by
any means without permission in writing from
Wordware Publishing, Inc.
Printed in the United States of America
ISBN 1-55622-752-3
10987654321
0210
Delphi is a registered trademark of Borland Software Corporation in the United States and other countries. Other products
mentioned are used for identification purposes only and may be trademarks of their respective companies.
All inquiries for volume purchases of this book should be addressed to Wordware Publishing, Inc., at the above
address. Telephone inquiries may be made by calling:

(972) 423-0090
Dedications
To Ann, with all my love.
Alan C. Moore
To the memory of my dear mum, Marie Chisholm Penman, who passed away on
March 11, 2001.
John C. Penman
iii

Contents
Acknowledgments xiv
Introduction xvii
Part I: Winsock
Chapter 1: The Winsock API 3
Introduction 3
In the Beginning 3
Network Protocols 5
The OSI Network Model 1 6
Before Winsock 7
Evolution of Winsock 8
The Winsock Architecture 9
Winsock 1.1 9
Winsock 2 10
New Features of Winsock 11
Multiple Protocol Support 11
Name Space Independence 11
Scatter and Gather 11
Overlapped I/O 11
Quality of Service 11
Multipoint and Multicast 12

Conditional Acceptance 12
Connect and Disconnect Data 12
Socket Sharing 12
Protocol-specific Addition 12
Socket Groups 12
Summary 13
Chapter 2: Winsock Fundamentals 15
Starting and Closing Winsock 15
function WSAStartup 16
function WSACleanup 19
Handling Winsock Errors 22
Errorsanderrors 23
function WSAGetLastError 24
procedure WSASetLastError 25
v
The Many Faces of the Winsock DLL 27
Summary 28
Chapter 3: Winsock 1.1 Resolution 29
Translation Functions 30
function htonl 31
function htons 32
function ntohl 32
function ntohs 33
Miscellaneous Conversion Functions 34
function inet_addr 34
function inet_ntoa 35
Resolution 37
Resolving Using a HOSTS file 38
Resolving Using DNS 39
Resolving Using a Local Database File with DNS 40

Blocking and Asynchronous Resolution 40
Host Resolution 42
function gethostbyaddr 42
function gethostbyname 45
function gethostname 47
function WSAAsyncGetHostByName 48
function WSAAsyncGetHostByAddr 54
Service Resolution 55
function getservbyname 55
function getservbyport 58
function WSAAsyncGetServByName 60
function WSAAsyncGetServByPort 61
Protocol Resolution 62
function getprotobyname 62
function getprotobynumber 64
function WSAAsyncGetProtoByName 66
function WSAAsyncGetProtoByNumber 67
Canceling an Outstanding Asynchronous Call 68
function WSACancelAsyncRequest 68
Summary 69
Chapter 4: Winsock 2 Resolution 71
Translation Functions 71
function WSAHtonl 71
function WSAHtons 74
function WSANtohl 74
function WSANtohs 75
Address and String Conversion Functions 76
function WSAAddressToString 76
vi
Contents

function WSAStringToAddress 78
Enumerating Network Protocols 79
function WSAEnumProtocols 86
Name Space Resolution and Registration 87
Enumerating Name Spaces 88
function WSAEnumNameSpaceProviders 89
Registering a Service 91
function WSAInstallServiceClass 95
function WSASetService 102
function WSARemoveServiceClass 102
Service Queries 103
function WSALookupServiceBegin 105
function WSALookupServiceNext 109
WSALookupServiceEnd 112
Helper Functions 112
function WSAGetServiceClassInfo 112
function WSAGetServiceClassNameByClassId 113
Functions for the Future 115
Making Your Winsock Applications Agnostic 116
function getaddrinfo 119
procedure freeaddrinfo 126
function getnameinfo 126
function gai_strerror 132
Obsolete Functions 132
Summary 133
Chapter 5: Communications 135
The Mechanics of Data Exchange 136
Socket Creation 137
function socket 141
function WSASocket 143

Making the Connection 144
function connect 147
function WSAConnect 149
function getpeername 154
function getsockname 155
Sending Data 160
function send 161
function WSASend 162
function sendto 163
function WSASendTo 164
Receiving Data 165
function recv 165
function WSARecv 166
function recvfrom 168
vii
Contents
function WSARecvfrom 169
Breaking the Connection 170
function shutdown 172
function closesocket 172
function WSASendDisconnect 173
function WSARecvDisconnect 174
Server Applications 174
Preparation 174
Duplicated Sockets 178
function bind 179
function listen 179
function accept 180
function WSAAccept 181
function WSADuplicateSocket 182

I/O Schemes 183
Using Select 183
Using WSAAsyncSelect 185
Using WSAEventSelect 188
Using Overlapped Routines 191
Event Notification 192
Completion I/O Schemes 193
Completion Port I/O Scheme 194
Which I/O Scheme to Use? 195
To Block or Not to Block? 196
Winsock and Multithreading 198
function select 203
function WSAAsyncSelect 203
function WSACreateEvent 210
function WSAWaitForMultipleEvents 215
function WSAEnumNetworkEvents 220
function WSAEventSelect 221
function WSACloseEvent 222
function WSAResetEvent 222
function WSASetEvent 223
function WSAGetOverlappedResult 224
Raw Sockets 225
Microsoft Extensions to Winsock 2 239
function AcceptEx 241
procedure GetAcceptExSockaddrs 242
function TransmitFile 243
function WSARecvEx 245
Microsoft Extensions to Winsock 2 for Windows XP and
Windows .NET Server 246
function ConnectEx 247

function DisconnectEx 248
viii
Contents
function TransmitPackets 249
function WSANSPIoctl 251
function WSARecvMsg 252
IP Multicast 253
What is IP Multicast? 253
What Can You Do with IP Multicast? 255
How Do You Develop a Simple IP Multicast Application? 256
function WSAJoinLeaf 258
Obsolete Functions 261
function WSACancelBlockingCall 261
function WSAIsBlocking 262
function WSASetBlockingHook 263
function WSAUnhookBlockingHook 264
Summary 264
Chapter 6: Socket Options 265
Querying and Modifying Attributes 265
Option Level = SOL_SOCKET 270
Option = SO_DEBUG 270
Option = SO_KEEPALIVE 270
Option = SO_LINGER 271
Option = SO_REUSEADDR 271
Option = SO_RCVBUF and SO_SNDBUF 272
Option Level = IPPROTO_TCP 272
Option = TCP_NODELAY 272
Option Level = IPPROTO_IP 272
Option = IP_OPTIONS 272
Option = IP_HDRINCL 273

Option = IP_TOS 273
Option = IP_TTL 273
Option = IP_MULTICAST_IF 274
Option = IP_MULTICAST_TTL 274
Option = IP_MULTICAST_LOOP 274
Option = IP_ADD_MEMBERSHIP 274
Option = IP_DROP_MEMBERSHIP 274
Option = IP_DONTFRAGMENT 274
Modifying I/O Behavior 274
function getsockopt 278
function setsockopt 279
function ioctlsocket 279
function WSAIoctl 280
Summary 281
ix
Contents
Part 2: TAPI
Chapter 7: Introduction to TAPI 285
An Historical Review 286
The World of Telephony Applications 287
The Elements of a Telephony System 290
Nature and Structure of TAPI 292
Media Stream 294
Varieties of Physical Connections 295
Levels of Telephony Programming Using TAPI 297
Summary 304
Chapter 8: Line Devices, Essential Operations 305
Stages in Working with Telephony 306
Three Notification Mechanisms 307
TAPI Line Support—Basic and Extended Capabilities 309

Determining Capabilities and Configuring TAPI 309
Configuring TAPI 311
TAPI’s VarString 312
Line Initialization—Making a Connection with TAPI 313
Let’s Negotiate 317
Determining Capabilities 318
Opening a Line Device 319
Give Me Your ID 320
Specifying Media Modes 321
Working with Media Modes 322
Closing a Line Device 325
Reference for Basic TAPI Functions 326
function lineClose 327
function lineConfigDialog 327
function lineConfigDialogEdit 328
function lineGetAddressCaps 330
structure LINEADDRESSCAPS 332
structure LINECALLTREATMENTENTRY 346
function lineGetAddressID 347
function lineGetAddressStatus 348
structure LINEADDRESSSTATUS 349
LINEADDRFEATURE Constants 353
function lineGetDevCaps 355
structure LINEDEVCAPS 356
LINEFEATURE_ Constants 365
structure LINETERMCAPS 365
structure LINETRANSLATECAPS 366
structure LINECARDENTRY 367
structure LINELOCATIONENTRY 369
x

Contents
TEAMFLY






















































Team-Fly
®

LINELOCATIONOPTION_ Constants 371
function lineGetDevConfig 372

function lineGetID 373
function lineGetLineDevStatus 375
structure LINEDEVSTATUS 376
structure LINEAPPINFO 378
function lineGetTranslateCaps 379
function lineInitialize 380
function lineInitializeEx 382
function lineNegotiateAPIVersion 384
function lineNegotiateExtVersion 386
function lineOpen 387
function lineSetDevConfig 391
function lineShutdown 392
function lineGetCountry 393
structure LINECOUNTRYLIST 394
structure LINECOUNTRYENTRY 395
function lineGetIcon 396
function lineSetAppSpecific 397
function lineSetCurrentLocation 398
Summary 399
Chapter 9: Handling TAPI Line Messages 401
Line Callback 401
function TLineCallback 401
Issues Involving Messages 416
LINE_ADDRESSSTATE Message 417
LINE_AGENTSPECIFIC Message 418
LINE_AGENTSTATUS Message 418
LINE_APPNEWCALL Message 419
LINE_CALLINFO Message 420
LINE_CALLSTATE Message 422
LINE_CLOSE Message 426

LINE_CREATE Message 427
LINE_DEVSPECIFIC Message 428
LINE_DEVSPECIFICFEATURE Message 428
LINE_GATHERDIGITS Message 428
LINE_GENERATE Message 429
LINE_LINEDEVSTATE Message 430
LINE_MONITORDIGITS Message 433
LINE_MONITORMEDIA Message 434
LINE_MONITORTONE Message 435
LINE_PROXYREQUEST Message 436
LINE_REMOVE Message 437
LINE_REPLY Message 438
xi
Contents
LINE_REQUEST Message 438
LINE_AGENTSESSIONSTATUS Message 439
LINE_QUEUESTATUS Message 439
LINE_AGENTSTATUSEX Message 440
LINE_GROUPSTATUS Message 440
LINE_PROXYSTATUS Message 441
LINE_APPNEWCALLHUB Message 441
LINE_CALLHUBCLOSE Message 442
LINE_DEVSPECIFICEX Message 442
LINEPROXYREQUEST_ Constants 442
Functions Related to Message Handling 444
function lineGetMessage 444
structure LINEINITIALIZEEXPARAMS 445
LINEINITIALIZEEXOPTION_ Constants 445
structure LINEMESSAGE 446
function lineGetStatusMessages 447

function lineSetStatusMessages 448
function lineSetCallPrivilege 449
Chapter 10: Placing Outgoing Calls 451
Canonical and Dialable Address Formats 451
Assisted Telephony 453
TAPI Servers in Assisted Telephony 457
Assisted Telephony Functions 458
function tapiRequestMakeCall 459
function tapiGetLocationInfo 460
Establishing a Call with Low-Level Line Functions 461
Special Dialing Support 464
function lineDial 465
function lineMakeCall 466
structure LINECALLPARAMS 468
LINECALLPARAMFLAGS_ Constants 473
function lineTranslateAddress 474
structure LINETRANSLATEOUTPUT 477
function lineTranslateDialog 479
Summary 480
Chapter 11: Accepting Incoming Calls 481
Finding the Right Application 481
Unknown Media Type 483
Prioritizing Media Modes 484
Responsibilities of the Receiving Application 485
Media Application Duties 486
Accepting an Incoming Call 487
Ending a Call 493
xii
Contents
Reference for Additional Basic TAPI Functions 494

function lineAccept 494
function lineAnswer 496
function lineDeallocateCall 497
function lineDrop 498
function lineGetCallInfo 499
structure LINECALLINFO 500
function lineGetCallStatus 508
structure LINECALLSTATUS 509
function lineGetConfRelatedCalls 510
function lineGetNewCalls 511
structure LINECALLLIST 513
function lineGetNumRings 513
function lineGetRequest 514
structure LINEREQMAKECALL 515
structure LINEREQMEDIA 516
function lineHandoff 517
function lineRegisterRequestRecipient 519
LINEREQUESTMODE_ Constants 520
function lineSetNumRings 520
function lineSetTollList 521
Appendix A: Glossary of Important Communications Programming
Terms 525
Appendix B: Error Codes, Their Descriptions, and Their Handling 531
Appendix C: Bibliography of Printed and Online Communications
Programming Resources 543
Index 547
xiii
Contents
Acknowledgments
Writing a book like this is a major endeavor. I want to take this opportunity to

thank some of the many people who helped make it possible. First, let me thank
my wife, Ann, and daughter, Treenah, for their support and patience during the
many hours I spent in front of a computer screen coding and writing. My col
-
leagues at Kentucky State University have also been very supportive, especially
my new chairperson, Dr. Barbara Buck, who provided much encouragement for
my writing.
There are several people and one organization that had a great deal to do with
my getting involved with TAPI in the first place. The organization is Project
JEDI, which produced the translation of the TAPI header file for use in Delphi.
The pioneering work of the original translators, Alexander Staubo and Brad
Choate, was followed by the excellent new translation by Marcel van Brakel,
with contributions from Rudy Velthuis and myself.
The TAPI portion of this book is based to some extent on a series of articles I
wrote in Delphi Informant Magazine beginning in the late 1990s. Thanks to my
good friend Jerry Coffey, the editor of Delphi Informant Magazine, for his contin-
ued encouragement to explore and write about TAPI. Thanks also to Major Ken
Kyler, with whom I wrote the first three articles. Ken provided me with my first
introduction to the world of TAPI. I would be remiss if I did not acknowledge my
current co-author, John Penman. In the process of writing this book, we have
read each other’s text in some detail. Working with John on this book has been
delightful from the start. Finally, let me acknowledge my excellent technical edi
-
tor, Gary Frerking, president of TurboPower. He was extremely helpful in
identifying portions of the text that were not clear and code that needed further
work.
Before closing, I want to acknowledge the importance of my guru and spiri
-
tual teacher, the late Chogyam Trungpa, Rinpoche. The meditative disciplines
he introduced to me and so many others have helped make my life more full and

productive.
Alan C. Moore
xiv
As with any programming project, there are team players, project leaders, and
technical staff. In this context, Alan and I are project leaders who have written
this book, but without the team players and technical staff, there wouldn’t be a
book for us to write and you to read and hopefully assimilate some useful knowl
-
edge. So, it is in this vein that I would like to thank the team players for their
contribution to making this book a reality. First, a special thanks must go to
Marcel van Brakel, a former JEDI knight of Project JEDI (www.jedi.org), who
gave some of his valuable time to test and debug all of the Winsock examples, as
well as provide constructive criticism and suggestions for the chapters. I would
also like to thank Chad Z. Hower for undertaking the role of technical editor for
the Winsock chapters, which he carried out so ably. To those two guys, thanks a
million!
I would also like to thank Alan C. Moore for his encouragement and wit dur
-
ing the time we worked together on the book. You will be amazed to know that
we have never met in person, but we forged an excellent friendship through our
electronic collaboration on this book. Perhaps we will collaborate on another!
I would like to thank Jim Hill, Wes Beckwith, and the hard-working staff at
Wordware Publishing for their unfailing patience in spite of numerous missed
milestones.
To end on a personal note, I would like to express heartfelt thanks to my dad
for his unstinting and uncomplaining support for me while I was on contract in
Scotland during the last 18 months. Thanks for being a great dad.
Finally, I must thank my dear wife, Jocie, and my two children, David and
Diana, for their loving support during the development of this tome.
John C. Penman

xv
Acknowledgments

Introduction
Reliable communications using computers has been important for a long time,
starting with DOS bulletin boards and the early days of the Internet. In this
book, we will provide an introduction to two of the essential communications
technologies, Windows Sockets (Winsock), the backbone of the Internet on the
Windows platform, and the Telephony Application Programming Interface
(TAPI).
We will provide a complete introduction to Winsock and basic TAPI. We had
originally planned on covering many of the other Internet technologies and the
entire TAPI, but discovered that the material was too extensive to do justice to
any of these technologies. We plan to write another book dealing with advanced
communications programming in which we will cover the more difficult and
newer topics. Nevertheless, this work should provide all that you will need to
write useful Internet/Intranet or telephony applications. The advanced book will
build on this foundation and provide the means for going beyond basic
functionality.
This book is organized into two parts. Part I, written by John C. Penman, is a
complete introduction to Winsock programming. Chapter 1 provides an intro-
duction to this technology and a description of the Winsock-related chapters
that follow. Part II, written by Alan C. Moore, is a complete introduction to basic
TAPI programming. Chapter 7 provides an introduction to this technology and a
description of the TAPI-related chapters that follow. As in other volumes in
Wordware Publishing’s Tomes of Delphi series, most chapters include introduc
-
tory sections on the various technologies, a complete reference to functions,
structures, and constants, and Delphi code examples.
The book concludes with three appendices providing a glossary of essential

communications terms, information about error handling in Winsock and TAPI,
and printed and Internet resources that provide additional information and pro
-
gramming materials.
Let’s begin the journey!
xvii

Part I
Internet/Intranet
Programming with
Winsock
by John C. Penman
n
Chapter1—TheWinsock API
n
Chapter 2 — Winsock Fundamentals
n
Chapter 3 — Winsock 1.1 Resolution
n
Chapter 4 — Winsock 2 Resolution
n
Chapter 5 — Communications
n
Chapter 6 — Socket Options
TEAMFLY























































Team-Fly
®

Chapter 1
The Winsock API
Introduction
In this chapter, we’ll outline the development of the Internet and the transport
protocols that underpin it. We’ll review the evolution of the Winsock Application
Programming Interface (API) from its origins. We will also examine the
Winsock 1.1 and 2 architectures, with particular emphasis on Winsock 2.
In the world of Windows, Winsock provides the crucial foundation upon which
all Internet applications run. Without Winsock, there would be no web brows-

ers, no file transfer, and none of the e-mail applications that we take so much for
granted in today’s Windows environment. Technologies like DCOM and n-tier
database systems would be difficult to implement.
Winsock is an API that is an integral part of Microsoft’s Windows Open Sys-
tems Architecture (WOSA), which we’ll discuss later in this chapter, as well as
in the second half of the book dealing with TAPI. Let’s start with the history of
the genesis of the Internet to the present.
In the Beginning
Nowadays, it’s easy to forget that the genesis of the Internet arose as a need for
a dependable and robust communication network for military and government
computers in the United States of America. In response to this need, in 1969
the Defense Advanced Research Projects Agency (DARPA) sponsored an exper
-
imental network called Advanced Research Projects Agency Network
(ARPANET).
Before the birth of ARPANET, for one computer to communicate with
another on a network, both machines had to come from the same vendor. We
call this arrangement a homogeneous network. In contrast, ARPANET, a collec
-
tion of different computers linked together, was a heterogeneous network.
As ARPANET developed, it became popular for connected institutions to
accomplish daily tasks such as e-mail and file transfer. In 1975, ARPANET
became operational. However, as you might have already guessed, research into
network protocols continued. Network protocols that developed early in the life
3
of ARPANET evolved into a set of network protocols called the Transmission
Control Protocol/Internet Protocol (TCP/IP) suite. The TCP/IP protocol suite
became a Military Standard in 1983, which made it mandatory for all computers
on ARPANET to use TCP/IP.
2

NOTE: For brevity, we use TCP/IP as a shorthand for TCP/IP suite.
In 1983, ARPANET split into two networks: MILNET for unclassified military
use and ARPANET, which was the smaller of the two, for experimental
research. These networks became known as the Internet.
2
NOTE: The meaning of the Internet is just a collection of smaller
networks to form a large network. Therefore, we can use the
generic term internet to refer to a network of smaller networks
that is not the Internet.
The Internet expanded further when DARPA invited more universities to use
the Internet for research and communications. In the early 1980s, however, uni-
versity computer sites were using the Berkeley Software Distribution (BSD)
UNIX, a variant of UNIX that did not have TCP/IP. DARPA funded Bolt Beranek
and Newman, Inc. to implement TCP/IP in BSD UNIX. Thus, TCP/IP became
an intimate part of UNIX.
Although TCP/IP became an important communications provider in BSD
UNIX, it was still difficult to develop network applications. Programmers at the
University of Berkeley created an abstract layer to sit on top of TCP/IP, which
became known as the Sockets layer. The version of BSD UNIX that incorporated
the Sockets layer for the first time was 4.2BSD, which was released in August
1983.
The Sockets layer made it easier and quicker to develop and maintain net
-
work applications. The Sockets layer became a catalyst for the creation of
network applications, which further fueled the expansion of the Internet. With
the expansion of the Internet, TCP/IP became the network protocol of choice.
The following properties of TCP/IP explain the rapid acceptance of TCP/IP:
n
It is vendor independent, meaning an open standard.
n

It is a standard implementation on every computer from PCs to
supercomputers.
n
It is used in local area networks (LANs) and wide area networks (WANs).
n
It is used by commercial entities, government agencies, and universities.
4
n
Chapter 1
The Internet’s rapid growth (and its continued growth) owes much to the devel
-
opment of the Hypertext Transfer Protocol (HTTP) that has provided the
underpinnings for the World Wide Web. Rightly or wrongly, the ordinary man
and woman on the street now sees the World Wide Web as the
Internet.
Internet protocols like HTTP, FTP, SMTP, and POP3 are high-level protocols
that operate seamlessly on top of the network protocols collectively known as
the TCP/IP protocol suite, or just TCP/IP. We’ll describe briefly the network
protocols that constitute the TCP/IP protocol suite in the next section.
Network Protocols
TCP/IP is a suite of network protocols upon which higher-level protocols, such
as FTP, HTTP, SMTP, and POP3, operate. This suite comprises the two major
protocols (TCP and IP) and a family of other protocols. We enumerate these as
follows:
n
Transmission Control Protocol (TCP) is a connection-based protocol
that provides a stable, full duplex byte stream for an application. Applica-
tions like FTP and HTTP use this protocol.
n
User Datagram Protocol (UDP) is a connectionless protocol that pro-

vides unreliable delivery of datagrams. (Note: Do not confuse “unreliable”
with quality in this context. Unreliable refers to the possibility that some
datagrams may not arrive at their destination, become duplicated, or
arrive out of sequence.) IP Multicast applications use this protocol.
n
Internet Control Message Protocol (ICMP) is a protocol that handles
error and control information between hosts. Applications like ping and
traceroute use this protocol.
n
Internet Protocol (IP) is a protocol that provides packet delivery for
TCP, UDP, and ICMP.
n
Address Resolution Protocol (ARP) is a protocol that maps an Internet
address into a hardware address.
n
Reverse Address Resolution Protocol (RARP) is a protocol that maps a
hardware address into an Internet address.
Fortunately, the BSD Sockets layer insulated the programmer from these proto
-
cols and, with some exceptions, most network applications did not need to know
the intimate details of TCP/IP.
The Winsock API
n
5
1
Chapter
The OSI Network Model 1
In 1977, the International Organization for Standardization (ISO) created a refer
-
ence schema for networking computers together. This networking model is a

guide, not a specification, for the construction of any network. This guide, Open
System Interconnection (OSI), states that a network should provide seven lay
-
ers, as explained in Figure 1-1.
If we map TCP/IP using the OSI network model, we get the following simplified
diagram in Figure 1-2.
6
n
Chapter 1
Figure 1-1
Figure 1-2

×