www.free-ebooks-download.org TCP/IP Sockets in C# Practical Guide for Programmers www.free-ebooks-download.org The Morgan Kaufmann Practical Guides Series Series Editor: Michael J. Donahoo TCP/IP Sockets in C#: Practical Guide for Programmers David Makofske, Michael J. Donahoo, and Kenneth L. Calvert Java Cryptography Extensions: Practical Guide for Programmers Jason Weiss JSP: Practical Guide for Java Programmers Robert J. Brunner JSTL: Practical Guide for JSP Programmers Sue Spielman Java: Practical Guide for Programmers Zbigniew M. Sikora The Struts Framework: Practical Guide for Java Programmers Sue Spielman Multicast Sockets: Practical Guide for Programmers David Makofske and Kevin Almeroth TCP/IP Sockets in Java: Practical Guide for Programmers Kenneth L. Calvert and Michael J. Donahoo TCP/IP Sockets in C: Practical Guide for Programmers Michael J. Donahoo and Kenneth L. Calvert JDBC: Practical Guide for Java Programmers Gregory D. Speegle For further information on these books and for a list of forthcoming titles, please visit our website at http://www.mkp.com/practical TCP/IP Sockets in C# Practical Guide for Programmers David B. Makofske Akamai Technologies Michael J. Donahoo Baylor University Kenneth L. Calvert University of Kentucky AMSTERDAM • BOSTON • HEIDELBERG • LONDON NEW YORK • OXFORD • PARIS • SAN DIEGO SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO Morgan Kaufmann is an imprint of Elsevier Senior Editor Rick Adams Associate Editor Karyn Johnson Publishing Services Manager Simon Crump Project Manager Kyle Sarofeen Cover Design Yvo Niezebos Design Cover Image Getty Images Composition Cepha Imaging Pvt. Ltd. Copyeditor Harbour Fraser Hodder Proofreader Jacqui Brownstein Indexer Michael Ferreira Interior printer Maple Press Cover printer Phoenix Color Morgan Kaufmann Publishers is an imprint of Elsevier. 500 Sansome Street, Suite 400, San Francisco, CA 94111 This book is printed on acid-free paper. ©2004 by Elsevier Inc. All rights reserved. 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 contact 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 means—electronic, mechanical, photocopying, scanning, or otherwise—without prior written permission of the publisher. Permissions may be sought directly from Elsevier’s Science & Technology Rights Department in Oxford, UK: phone: (+44) 1865 843830, fax: (+44) 1865 853333, e-mail: permissions@elsevier.com.uk. You may also complete your request on-line via the Elsevier homepage (http://elsevier.com)by selecting “Customer Support” and then “Obtaining Permissions.” Library of Congress Cataloging-in-Publication Data Application submitted. ISBN: 0-12-466051-7 For information on all Morgan Kaufmann publications, visit our Web site at www.mkp.com Printed in the United States of America 0807060504 54321 For Margie and Jacob, for their love and inspiration –David For my three girls: Lisa, Michaela, and Mackenzie –Jeff For my parents, Paul and Eleanor Calvert –Ken This Page Intentionally Left Blank Contents Preface ix 1 Introduction 1 1.1 Networks, Packets, and Protocols 1 1.2 About Addresses 4 1.3 About Names 5 1.4 Clients and Servers 5 1.5 What Is a Socket? 6 1.6 Exercises 7 2 Basic Sockets 9 2.1 Socket Addresses 9 2.2 Socket Implementation in .NET 15 2.3 TCP Sockets 16 2.4 UDP Sockets 29 2.5 The .NET Socket Class 37 2.6 Exercises 57 3 Sending and Receiving Messages 59 3.1 Encoding Information 61 3.2 Composing I/O Streams 65 3.3 Framing and Parsing 66 3.4 Implementing Wire Formats in C# 70 3.5 Wrapping Up 83 3.6 Exercises 84 vii viii Contents ■ 4 Beyond the Basics 85 4.1 Nonblocking I/O 85 4.2 Multiplexing 95 4.3 Threads 99 4.4 Asynchronous I/O 117 4.5 Multiple Recipients 131 4.6 Closing Connections 138 4.7 Wrapping Up 145 4.8 Exercises 146 5 Under the Hood 147 5.1 Buffering and TCP 149 5.2 Buffer Deadlock 152 5.3 Performance Implications 154 5.4 TCP Socket Life Cycle 155 5.5 Demultiplexing Demystified 165 5.6 Exercises 167 Appendix: Handling Socket Errors 169 Bibliography 171 Index 173 Preface For years, college courses in computer networking were taught with little or no “hands on” experience. For various 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 ideal world this would suffice, 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 students (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 communication services that might be implemented by whatever protocols were supported on a particular platform—IPX, Appletalk, TCP/IP, and so on. As a conse- quence of this generic approach the sockets API may appear dauntingly complicated at first. But, in fact, the basics of network programming using the Internet (TCP/IP) proto- cols are not difficult. The sockets interface has been around for a long time—at 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 courses. 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 provide a gentle ix [...]... Web server for the publisher of this text, Morgan Kaufmann, changed Internet addresses from 213 .38 .16 5 .18 0 to 12 9.35.78 .17 8 However, because we refer to that Web server as www.mkp.com (clearly much easier to remember than 213 .38 .16 5 .18 0), and because the change is reflected in the system that maps names to addresses (www.mkp.com now resolves to the new Internet address instead of 213 .38 .16 5 .18 0), the... services through the sockets application programming interface (API) The goal of this book is to get you started writing programs that use the sockets API Before 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 fits in Our goal here is not to teach you how networks and TCP/IP work—many... it takes two pieces of information to identify a particular program: an Internet address, used by IP, and a port number, the additional address interpreted by the transport protocol (TCP or UDP) Internet addresses are 32-bit binary numbers .1 In writing down Internet addresses for human consumption (as opposed to using them inside applications), we typically show them as a string of four decimal numbers... network Information written to the socket by an application on one machine can be read by an application on a different machine, and vice versa Different types of sockets correspond to different underlying protocol suites and different stacks of protocols within a suite This book deals only with the TCP/IP protocol suite The main types of sockets in TCP/IP today are stream sockets and datagram sockets. .. control information to figure out how to forward each packet A protocol is an agreement about the packets exchanged by communicating programs and what they mean A protocol tells how packets are structured for example, where the destination information is located in the packet and how big it is—as well as how the information is to be interpreted A protocol is usually designed to solve a specific problem using... 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 to a Microsoft Windows OS that can install and run the NET Framework Software Development Kit (SDK )1 and has access to the Internet (or some other TCP/IP. .. generally remain blissfully unaware of their existence By information we here mean a sequences of bytes that are constructed and interpreted by programs In the context of computer networks these byte sequences are generally called packets A packet contains control information that the network uses to do its job and sometimes also includes user data An example is information about the packet’s destination... We will maintain an errata list on the book’s Web page Finally, we are grateful to the folks at Morgan Kaufmann, especially our editor Karyn Johnson and project manager Mamata Reddy For Further Information This book has a website (www.mkp.com /practical/ csharpsockets) that contains additional information, including all the source code presented in the book and errata From time to time, we may also place... used in the Internet, but it can be used in stand-alone private networks as well; henceforth when we say “the network,” we mean any network that uses the TCP/IP protocol family The main protocols in the TCP/IP family are the Internet Protocol (IP), the Transmission Control Protocol (TCP), and the User Datagram Protocol (UDP) It turns out to be useful to organize protocols in a family into layers; TCP/IP. ..x Preface ■ introduction, 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 benefits First, for a surprising number of people, socket programming is their first exposure to concrete realizations of concepts previously seen only in the abstract Dealing with the . Sockets: Practical Guide for Programmers David Makofske and Kevin Almeroth TCP/IP Sockets in Java: Practical Guide for Programmers Kenneth L. Calvert and Michael J. Donahoo TCP/IP Sockets in C: Practical. www.free-ebooks-download.org TCP/IP Sockets in C# Practical Guide for Programmers www.free-ebooks-download.org The Morgan Kaufmann Practical Guides Series Series Editor: Michael J. Donahoo TCP/IP Sockets in C#: Practical. 57 3 Sending and Receiving Messages 59 3 .1 Encoding Information 61 3.2 Composing I/O Streams 65 3.3 Framing and Parsing 66 3.4 Implementing Wire Formats in C# 70 3.5 Wrapping Up 83 3.6 Exercises