Chapter 16. Networking

16.0. Introduction

.NET provides many classes to help make network programming easier than many environments that preceded it. There is a great deal of functionality to assist you with tasks such as:

  • Building network-aware applications.

  • Downloading files via FTP.

  • Sending and receiving HTTP requests.

  • Getting a higher degree of control using TCP/IP and sockets directly.

In the areas in which Microsoft has not provided managed classes to access networking functionality (such as some of the methods exposed by the WinInet API for Internet connection settings), there is always P/Invoke, so you can code to the Win32 API; you’ll explore this in this chapter. With all of the functionality at your disposal in the System.Net namespaces, you can write network utilities very quickly. Let’s take a closer look at just a few of the things this section of .NET provides you access to.

16.1. Writing a TCP Server

Problem

You need to create a server that listens on a port for incoming requests from a TCP client. These client requests can then be processed at the server, and any responses can be sent back to the client. Recipe 16.2 shows how to write a TCP client to interact with this server.

Solution

Use the MyTcpServer class created here to listen on a TCP-based endpoint for requests arriving on a given port:

	class MyTcpServer
	{ 
	    #region Private Members 
	    private TcpListener _listener;
	    private IP Address _address; 
	    private int _port; private bool _listening; private object _syncRoot = new object(); ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.