讲义文稿成果tcpip sockets in c非扫描_第1页
讲义文稿成果tcpip sockets in c非扫描_第2页
讲义文稿成果tcpip sockets in c非扫描_第3页
讲义文稿成果tcpip sockets in c非扫描_第4页
讲义文稿成果tcpip sockets in c非扫描_第5页
已阅读5页,还剩183页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、TCP/IP Sockets in C#Practical Guide for ProgrammersThe Morgan Kaufmann Practical Guides SeriesSeries Editor: Michael J. DonahooTCP/IP Sockets in C#: Practical Guide for ProgrammersDavid Makofske, Michael J. Donahoo, and Kenneth L. CalvertJava Cryptography Extensions: Practical Guide for ProgrammersJ

2、ason WeissJSP: Practical Guide for Java ProgrammersRobert J. BrunnerJSTL: Practical Guide for JSP ProgrammersSue SpielmanJava: Practical Guide for ProgrammersZbigniew M. SikoraThe Struts Framework: Practical Guide for Java ProgrammersSue SpielmanMulticast Sockets: Practical Guide for ProgrammersDavi

3、d Makofske and Kevin AlmerothTCP/IP Sockets in Java: Practical Guide for ProgrammersKenneth L. Calvert and Michael J. DonahooTCP/IP Sockets in C: Practical Guide for ProgrammersMichael J. Donahoo and Kenneth L. CalvertJDBC: Practical Guide for Java ProgrammersGregory D. SpeegleFor further informatio

4、n on these books and for a list of forthcoming titles, please visit our website atTCP/IP Sockets in C#Practical Guide for ProgrammersDavid B. MakofskeAkamai TechnologiesMichael J. DonahooBaylor UniversityKenneth L. CalvertUniversity of KentuckyAMSTERDAM BOSTON HEIDELBERG LONDON NEW YORK OXFORD PARIS

5、 SAN DIEGOSAN FRANCISCO SINGAPORE SYDNEY TOKYOMorgan Kaufmann is an imprint of ElsevierSenior Editor Associate EditorPublishing Services Manager Project ManagerCover Design Cover Image Composition Copyeditor Proofreader Indexer Interior printer Cover printerRick Adams Karyn Johnson Simon Crump Kyle

6、SarofeenYvo Niezebos Design Getty ImagesCepha Imaging Pvt. Harbour Fraser Hodder Jacqui Brownstein Michael FerreiraMaple Press Phoenix Color.Morgan Kaufmann Publishers is an imprint of Elsevier. 500 Sansome Street, Suite 400, San Francisco, CA 94111This book is printed on acid-free paper.2004 by Els

7、evier Inc.s.Designations used by companies to distinguish their products are often claimed as trademarks or registered trademarks. In all instances in which Morgan Kaufmann Publishers is aware of a claim, the product names appear in initial capital or all capital letters. Readers, however, should co

8、ntact the appropriate companies for more complete information regarding trademarks and registration.No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any meanselectronic, mechanical, photocopying, scanning, or otherwisewithout prior written

9、 permission of the publisher.Permissions may be sought directly from Elseviers Science & Technology Rights Department inOxford, UK: phone: (+44) 1865 843830, fax: (+44) 1865 853333,: permissions.uk.You may also complete your request on-line via the Elsevier homepage ( selecting “Customer Support” an

10、d then “Obtaining Permissions.”) byLibrary of Congress Cataloging-in-Publication DataApplication submitted.ISBN: 0-12-466051-7For information on all Morgan Kaufmann publications, visit our Web site atPrinted in the United States of America 08 07 06 05 04 5 4 3 2 1 For Margie and Jacob, for their lov

11、e and inspirationDavidFor my three girls: Lisa, Michaela, and MackenzieJeffFor my parents, Paul and Eleanor CalvertKenThis Page Intentionally Left BlankContentsPreface ix1Introduction Networks, Packets, and Protocols About Addresses41About Names5Clients and Servers What Is a Socke

12、t?6 Exercises752Basic Sockets Socket Addresses9Socket Implementation in .NET 15 TCP Sockets 16UDP Sockets 29The .NET Socket Class 37 Exercises 573Sending and Receiving Messages 5Encoding Information 61 Composing I/O Streams 65 Framing and Parsing 66Implementing

13、Wire Formats in C# 70 Wrapping Up 83Exercises 84viiviiiContents4Beyond the Basics 84.74.8Nonblocking I/O 85Multiplexing 95Threads 99Asynchronous I/O 117Multiple Recipients 131Closing Connections 138Wrapping Up 145Exercises 1465Under the Hood 14Buffering and TCP

14、149 Buffer Deadlock 152Performance Implications 154 TCP Socket Life Cycle 155 Demultiplexing Demystied 165Exercises 167Appendix: Handling Socket Errors 169Bibliography 171Index 173PrefaceFor years, college courses in computer networking were taught with little or no “hands on” experience. For variou

15、s reasons, including some good ones, instructors approached the principles of computer networking primarily through equations, analyses, and abstract descriptions of protocol stacks. Textbooks might include code, but it was unconnected to anything students could get their hands on. Perhaps in an ide

16、al world this would sufce, but we believe that students learn better when they can see (and then build) concrete examples of the principles at work. Fortunately, such examples abound today. The Internet has become a part of everyday life, and access to its services is readily available to most stude

17、nts (and their programs).The Berkeley Sockets interface, known universally as “sockets” for short, is the de facto standard application programming interface (API) for networking, spanning a wide range of operating systems. The sockets API was designed to provide generic access to interprocess commu

18、nication services that might be implemented by whatever protocolswere supported on a particular platformIPX, Applk, TCP/IP, and so on. As a conse-quence of this generic approach the sockets API may appear dauntingly complicated at rst. But, in fact, the basics of network programming using the Intern

19、et (TCP/IP) proto- cols are not difcult. The sockets interface has been around for a long timeat least in “Internet time”but it is likely to remain important for the foreseeable future.We have written this book to improve the support for socket-based programming exercises in our own networking cours

20、es. Although some networking texts deal with net- work programming, we know of none that cover TCP/IP sockets. Excellent reference books on TCP/IP socket programming exist, but they are too large and comprehensive to be con- sidered as a supplement to a networking text. Our goal, therefore, is to pr

21、ovide a gentleixxPrefaceintroduction, and a handy reference, that will allow students to dive right in without too much handholding.Enabling students to get their hands on real network services via the sockets interface has several benets. First, for a surprising number of people, socket programming

22、 is their rst exposure to concrete realizations of concepts previously seen only in the abstract. Dealing with the very real consequences of messy details, such as the layout of data struc- tures in memory, seems to trigger a kind of epiphany in some students, and this experience has consequences fa

23、r beyond the networking course. Second, we nd that students who understand how application programs use the services of TCP/IP generally have an easier time grasping the principles of the underlying protocols that implement those services. Finally, basic socket programming skills are a springboard t

24、o more advanced assignments, which support learning about routing algorithms, multimedia protocols, medium access control, and so on.Intended AudienceThis book is aimed primarily at students in introductory courses in computer networks, either upper-level undergraduate or graduate. It is intended as

25、 a supplement, to be used with a traditional textbook, that should explain the problems and principles of computer networks. At the same time, we have tried to make the book reasonably self-contained (except for the assumed background) so that it can also be used, for example, in courses on operatin

26、g systems or distributed computing. We have purposely limited the books coverage in order to keep its price low enough to be reasonable for a supplementary text for such a course. An additional target audience consists of practitioners who know some C# and want to learn sockets. This book should tak

27、e you far enough that you can start experimenting and learning on your own.We assume basic programming skills and experience with C# and Microsoft Windows. You are expected to be conversant with C# concepts such as classes, methods, interfaces, and basic inheritance. We assume that you have access t

28、o a Microsoft Windows OS thatcan install and run the .NET Framework Software Development Kit (SDK)1 and has accessto the Internet (or some other TCP/IP network). The .NET SDK is a free download availableat. This book uses version 1.1 of the .NET Framework, althoughthe code should also work with vers

29、ion 1.0. Most of our examples involve compiling and running programs from a DOS command line; we assume that you can deal with that, although Microsoft Visual Studio may be used as well.1If you prefer UNIX, there is also an open source implementation of the .NET development frameworkcalled Mono in t

30、he works. Seefor details.PrefacexiApproachChapter 1 provides a general overview of networking concepts. It is not, by any means, a complete introduction but rather is intended to allow readers to synchronize with the con- cepts and terminology used throughout the book. Chapter 2 introduces the mecha

31、nics of simple clients and servers; the code in this chapter can serve as a starting point for a variety of exercises. Chapter 3 covers the basics of message construction and parsing. The reader who digests the rst three chapters should in principle be able to implement a client and server for a giv

32、en (simple) application protocol. Chapter 4 then deals with techniques that are necessary when building more sophisticated and robust clients and servers. Finally, in keeping with our goal of illustrating principles through programming, Chapter 5 dis- cusses the relationship between the programming

33、constructs and the underlying protocol implementations in somewhat more detail.Our general approach introduces programming concepts through simple program examples accompanied by line-by-line commentary that describes the purpose of every part of the program. This lets you see the important objects

34、and methods as they are used in context. As you look at the code, you should be able to understand the purpose of each and every line of code.Our examples do not take advantage of all library facilities in the .NET framework. The .NET library includes hundreds of classes that can be used for network

35、ed applications that are beyond the scope of this book. True to its name, this book is about TCP/IP sockets programming, and it maintains a tight focus on the socket-related classes of .NET. Like- wise, we do not cover raw sockets programming or sockets programming using protocols other than TCP/IP.

36、 We do not include the WebRequest and WebResponse classes, or any of the System.Web classes. We believe that once you understand the principles, using these convenience classes will be straightforward. The network-relevant classes that we do cover include IPAddress, Dns, TcpClient, TcpListener, UdpC

37、lient, Socket, and their associated enumeration and helper classes.We include brief API summaries of the .NET classes discussed for convenience, but these are not complete summaries. Also, since .NET is relatively new and evolving, the reader is encouraged to utilize the full library reference on th

38、e Microsoft Developer Network website at for detailed descriptions, examples, and updates.This book is not an introduction to C# or the .NET framework. We expect that the reader is already acquainted with the language and basic .NET libraries (especially I/O), and knows how to develop programs in C#

39、. All the examples in this book are not necessarily production-quality code. Although we strive for robustness, the primary goal of our code examples is to educate. In order to avoid obscuring the principles with large amounts of error-handling code, we have sacriced some robustness for brevity and

40、clarity. We do not catch every exception that could occur, and in most cases we only catch exceptions that are particular to a class we are describing or a specic example we are trying to illustrate. Similarly, in order to avoid cluttering the examples with extraneous (nonsocket- related programming

41、) code, we have made them command-line based. While the booksxiiPrefacewebsite () contains an example of a GUI-enhancednetwork application, we do not include it or explain it in the text.AcknowledgmentsWe would like to thank all the people who helped make this book a reality. Despite the books brevi

42、ty, many hours went into reviewing the original proposal and the draft, and the reviewers input has signicantly shaped the nal result.First, thanks to those who meticulously reviewed the draft of the text and made suggestions for improvement. These include (in alphabetical order): Durgaprasad Gorti,

43、 Microsoft Corporation; Adarsh Khare, Microsoft Corporation; Mauro Ottaviani, Microsoft Corporation; and Dev Subramanian, Chalmers University of Technology. Any errors that remain are, of course, our responsibility. We are very interested in weeding out such errorsin future printings, so if you nd o

44、ne, please sendto any of us. We will maintain anerrata list on the books Wge.Finally, we are grateful to the folks at Morgan Kaufmann, especially our editor Karyn Johnson and project manager Mamata Reddy.For Further InformationThis book has a website () that contains additionalinformation, including

45、 all the source code presented in the book and errata. From time to time, we may also place new material on the website. We encourage you to take advantage of this resource, and to send us your suggestions for improvement of any aspect of this book. You can send feedback via the website maintained b

46、y the publisher, or you can sendusto the addresses below.David B. Makofske david_makofskeMichael J. Donahoo jeff_Kenneth L. Calvert c h a IntroMillions of computers all over the world are now connected to the worldwide network known as the Internet. The Internet

47、 enables programs running on computers thou-sands ofapart to communicate and exchange information. If you have a computerconnected to a network, you have undoubtedly used a Web browsera typical program that makes use of the Internet. What does such a program do to communicate with others over a netw

48、ork? The answer varies with the application and the operating system (OS), but a great many programs get access to network communication services through the “sock- ets” application programming interface (API). The goal of this book is to get you started writing programs that use the sockets API.Bef

49、ore delving into the details of the API, it is worth taking a brief look at the big picture of networks and protocols to see how an application programming interface for TCP/IP ts in. Our goal here is not to teach you how networks and TCP/IP workmany ne texts are available for that purpose 2, 4, 10,

50、 15, 20but rather to introduce some basic concepts and terminology.1.1Networks, Packets, and ProtocolsA computer network consists of machines interconnected by communication channels. We call these machines hosts and routers. Hosts are computers that run applications such as your Web browser, the ap

51、plication programs running on hosts are really the users of the network. Routers are machines whose job is to relay or forward information from one communication channel to another. They may run programs but typically do not run application programs. For our purposes, a communication channel is a me

52、ans of1p t e r 1duction2Chapter 1: Introductionconveying sequences of bytes from one host to another; it may be a broadcast technology like Ethernet, a dial-up modem connection, or something more sophisticated.Routers are important simply because it is not practical to connect every host directly to

53、 every other host. Instead, a few hosts connect to a router, which connects to other routers, and so on to form the network. This arrangement lets each machine get by with a relatively small number of communication channels; most hosts need only one. Programs that exchange information over the netwo

54、rk, however, do not interact directly with routers and generally remain blissfully unaware of their existence.By information we here mean a sequences of bytes that are constructed and inter- preted by programs. In the context of computer networks these byte sequences are gener-ally called packets. A

55、 packet contains control information that the network uses tosjob and sometimes also includes user data. An example is information about the packets destination. Routers use such control information to gure out how to forward each packet.A protocol is an agreement about the packets exchanged by comm

56、unicating programs and what they mean. A protocol tells how packets are structuredfor example, where the destination information is located in the packet and how big it isas well as how the information is to be interpreted. A protocol is usually designed to solve a specic problem using given capabil

57、ities. For example, the Hypertext Transfer Protocol (HTTP) solves the problem of transferring hypertext objects between servers where they are stored and Web browsers that make them available to human users.Implementing a useful network requires that a large number of different problems besolved. To keep thinanageable and modular, different protocols are designed to solvedifferent sets of problems. TCP/IP is one such collection of solutions, sometimes called a protocol suite. It happens to be the suite of protocols used in the Internet, but it can be used in stan

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论