Networking Programming with Microsoft .NET
Overview of Networking Basics
Why Study Networking?
Understanding networking is crucial because distributed applications are now widely used. These applications operate on computer networks, whether LANs or WANs, and involve multiple sites working together. Knowledge of networking is essential for developing such applications using .NET.
Networking Basics
Definitions
- Platform: Combination of hardware and operating system.
- Client: An application (e.g., a browser) that receives data from a server.
- Server: An application (e.g., IIS, Kestrel, Nginx) that provides data to clients.
- IP Address (Internet Protocol): An unsigned integer that uniquely identifies a network element.
- IPv4: A 4-byte IP address (e.g., 192.143.5.1).
- IPv6: A 16-byte IP address.
- Port: An unsigned 2-byte integer that helps the OS differentiate network communication processes.
- Protocol: Rules for packaging data in network communication, essential because clients and servers may operate on different platforms.
- TCP (Transmission Control Protocol): A connection-based protocol providing a reliable, ordered flow of data between two computers using an acknowledgment mechanism.
- UDP (User Datagram Protocol): A protocol that sends independent data packets (datagrams) without guarantees of arrival or order. It doesn't use an acknowledgment mechanism and may be blocked by firewalls or routers. It uses many connecting lines.
Client-Server Model
Communication Steps
- Client sends a request to the server: The request can be for a file (e.g., .html, .txt), a script file (e.g., .asp, .aspx, .php, .jsp), or to execute a method of a running object.
- Server analyzes and processes the request.
- Server sends a response to the client: The response may include the requested file or the result of processing.
Network Communication Layers
- Application Layer: Uses protocols like HTTP, FTP, or Telnet.
- Transport Layer: Uses protocols like TCP or UDP.
- Network Layer: Uses IP.
- Link Layer: Involves device drivers.
When data is transferred, each layer attaches a header (H) containing identifiable information to the package.
Distinguishing Computers and Processes
- Computer Identification: Achieved through IP addresses (e.g., 152.3.21.121) or hostnames. Personal computers often use the IP address 127.0.0.1.
- Process Identification: Each network-communicating process is distinguished by a port number. The physical connection is logically numbered within a range of 0 to 65535. Ports 0-1023 are reserved.
Example port assignments:
- 20, 21: FTP
- 23: Telnet
- 25: SMTP
- 161, 162: SNMP
URI, URL, and URN
- URI (Uniform Resource Identifier): A formatted string that identifies a resource on the internet or a LAN (e.g., web page, file, email address).
- Consists of elements like scheme, authority, and path.
- The
Uriclass in theSystemnamespace is used to divide a URI into its components.
- URL (Uniform Resource Locator): A subset of URI that specifies the network address or location of a resource.
- Begins with the protocol used to access the resource.
- URN (Uniform Resource Name): A URI that uses the "urn" scheme, followed by a namespace identifier and a namespace-specific string (e.g., urn:isbn:0451450523).
- URNs are location-independent and do not imply resource availability.
URI Demo
Example code demonstrating URI properties:
Uri info = new Uri("http://www.domain.com:80/info?id=123#fragment");
Uri page = new Uri("http://www.domain.com/info/page.html");
WriteLine($"Host: {info.Host}");
WriteLine($"Port: {info.Port}");
WriteLine($"PathAndQuery: {info.PathAndQuery}");
WriteLine($"Query: {info.Query}");
WriteLine($"Fragment: {info.Fragment}");
WriteLine($"Default HTTP port: {page.Port}");
WriteLine($"IsBaseOf: {info.IsBaseOf(page)}");
Uri relative = info.MakeRelativeUri(page);
WriteLine($"IsAbsoluteUri: {relative.IsAbsoluteUri}");
WriteLine($"RelativeUri: {relative.ToString()}");
.NET Networking Programming
System.Net.* Namespaces
The .NET framework provides various classes in the System.Net.* namespaces for network communication via HTTP, TCP/IP, and FTP.
Key components include:
- WebClient: A facade class for simple download/upload operations via HTTP or FTP.
- WebRequest and WebResponse: Classes for low-level control over client-side HTTP or FTP operations.
- HttpClient: For interacting with HTTP web APIs and RESTful services.
- HttpListener: Used for writing an HTTP server.
- SmtpClient: For constructing and sending email messages via SMTP.
- Dns: For converting between domain names and IP addresses.
- TcpClient, UdpClient, TcpListener, and Socket: Classes for direct access to transport and network layers.
Network Architecture Diagram
The diagram illustrates the location of .NET networking types within communication layers.
- The application layer is where
WebRequest,WebClient,WebResponse,SmtpClient,Dns,Ping,HttpClient,FtpWebRequest,HttpWebRequest, andHttpListenerreside. - The transport layer contains
TcpListener,TcpClient,UdpClient, andSocket. - The network and link layers deal with IP addresses and physical MAC addresses.
Understanding WebRequest and WebResponse Classes
WebRequest and WebResponse are abstract base classes for managing HTTP, FTP, and "file:" protocol client-side activities. They encapsulate the request/response model.
- WebRequest: An abstract base class for .NET's request/response model for accessing data from the Internet, enabling protocol-agnostic data requests.
Key WebRequest Properties:
- ContentLength: Gets or sets the content length of the request data being sent.
- ContentType: Gets or sets the content type of the request data being sent.
- Credentials: Gets or sets the network credentials used for authentication.
- Method: Gets or sets the protocol method (e.g., GET, POST).
- Headers: Gets or sets the collection of header name/value pairs.
- RequestUri: Gets the URI of the Internet resource.
- Timeout: Gets or sets the timeout in milliseconds.
Key WebRequest Methods:
- Create(Uri): Initializes a new WebRequest instance for the specified URI scheme.
- GetRequestStream(): Returns a Stream for writing data to the Internet resource.
- GetResponse(): Returns a response to an Internet request.
- CreateHttp(String): Initializes a new HttpWebRequest instance for the specified URI string.
- BeginGetRequestStream(AsyncCallback, Object): Provides an asynchronous version of GetRequestStream().
- BeginGetResponse(AsyncCallback, Object): Begins an asynchronous request for an Internet resource.
- Abort(): Aborts the request.
- WebResponse: An abstract base class from which protocol-specific response classes are derived. Client applications do not create WebResponse objects directly; they are created by calling GetResponse on a WebRequest instance.
Key WebResponse Properties and Methods:
- ContentLength: Gets or sets the content length of data being received.
- ContentType: Gets or sets the content type of the data being received.
- Headers: Gets a collection of header name-value pairs.
- IsFromCache: Indicates whether the response was obtained from the cache.
- Close(): Closes the response stream.
- GetResponseStream(): Returns the data stream from the Internet resource.
WebRequest & WebResponse Demo
WebRequest request = WebRequest.Create("http://www.contoso.com/default.html");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Status: " + response.StatusDescription);
Console.WriteLine(new string('*', 50));
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
Console.WriteLine(new string('*', 50));
reader.Close();
dataStream.Close();
response.Close();
Understanding HttpClient Class
HttpClient provides another layer on top of HttpWebRequest and HttpWebResponse. It was designed for interacting with HTTP-based web APIs and REST services.
- HttpClient is a newer API and works well with web APIs, REST-based services, and custom authentication schemes.
- In .NET Framework, HttpClient relied on WebRequest and WebResponse, but in .NET Core, it handles HTTP itself.
- HttpClient instances use their own connection pool, isolating requests.
- It offers a richer type system for headers and content and allows custom message handlers for extensibility.
Key HttpClient Properties:
- BaseAddress: Gets or sets the base URI for requests.
- MaxResponseContentBufferSize: Gets or sets the maximum buffer size for the response content.
- Timeout: Gets or sets the timespan to wait before a request times out.
Key HttpClient Methods:
- GetAsync(String): Sends a GET request to the specified URI.
- GetStringAsync(String): Sends a GET request and returns the response body as a string.
- PostAsync(String, HttpContent): Sends a POST request to the specified URI.
- PutAsync(String, HttpContent): Sends a PUT request to the specified URI.
- DeleteAsync(String): Sends a DELETE request to the specified URI.
HttpClient Class Demo-01
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
string uri = "http://www.contoso.com/";
try
{
HttpResponseMessage response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message : {0}", e.Message);
}
}
HttpClient Class Demo-02
This demo involves creating a WPF application named DemoHttpClient with a UI including a TextBox, Label, and Button.
XAML code snippets are provided for the MainWindow.xaml, showing Grid definitions with RowDefinitions and StackPanels to display the URL TextBox, HTML Source Label, Content TextBox, and Buttons (View HTML, Clear, Close).
Event handlers are implemented for the buttons:
- btnClose_Click: Closes the window.
- btnClear_Click: Clears the content TextBox.
- btnViewHTML_Click: Retrieves the HTML source from the specified URL using HttpClient and displays it in the content TextBox.
Understanding Domain Name System (DNS)
DNS translates domain names into IP addresses.
DNS Components:
- Name Space: Defines the syntactical rules for DNS names.
- Globally Distributed Database: Implemented on a network of name servers.
- Resolver: Software that formulates DNS queries.
DNS Demo
Console.WriteLine(new string('*', 30));
var domainEntry = Dns.GetHostEntry("www.contoso.com");
Console.WriteLine(domainEntry.HostName);
foreach (var ip in domainEntry.AddressList)
{
Console.WriteLine(ip);
}
Console.WriteLine(new string('*', 30));
var domainEntryByAddress = Dns.GetHostEntry("127.0.0.1");
Console.WriteLine(domainEntryByAddress.HostName);
foreach (var ip in domainEntryByAddress.AddressList)
{
Console.WriteLine(ip);
}
Console.ReadLine();
The System.Net.Sockets Namespace
Provides a managed implementation of the Windows Sockets (Winsock) interface.
Key Classes:
- Socket: Implements the Berkeley sockets interface.
- TcpClient: Provides client connections for TCP network services.
- TcpListener: Listens for connections from TCP network clients.
- UdpClient: Provides UDP network services.
- NetworkStream: Provides the underlying stream of data for network access.
- SocketAsyncEventArgs: Represents an asynchronous socket operation.
- SocketException: The exception thrown when a socket error occurs.
- SocketTaskExtensions: Contains extension methods to the Socket class.
Working with TCP Services
TCP services contain classes and methods for connecting and sending data between two or more points (IP address and port number).
The TcpClient and TcpListener classes create TCP connections and have methods/properties for connecting, sending, and receiving stream data.
The TcpListener Class
Provides methods to listen for and accept incoming connection requests in blocking synchronous mode.
Key Methods:
- AcceptSocket(): Accepts a pending connection request.
- AcceptSocketAsync(): Accepts a pending connection request asynchronously.
- AcceptTcpClient(): Accepts a pending connection request as a TcpClient.
- AcceptTcpClientAsync(): Accepts a pending connection request asynchronously as a TcpClient.
- Start(): Starts listening for incoming connection requests.
- Stop(): Closes the listener.
- Pending(): Determines if there are pending connection requests.
The TcpClient Class
Provides methods for connecting, sending, and receiving stream data over a network in synchronous blocking mode.
A TcpListener or Socket created with the TCP ProtocolType must be listening for incoming connection requests.
Two ways to connect:
- Create a TcpClient and call one of the Connect methods.
- Create a TcpClient using the host name and port number.
Key Properties:
- Active: Indicates whether a connection has been made
- Available: Gets the amount of data that has been received and is available to be read
- Client: Gets or sets the underlying Socket
- Connected: Indicates whether the Socket is connected to a remote host
- ReceiveBufferSize: Gets or sets the size of the receive buffer
- ReceiveTimeout: Gets or sets the timeout for receiving data
- SendBufferSize: Gets or sets the size of the send buffer
- SendTimeout: Gets or sets the timeout for sending data
Key Methods:
- Connect(IPAddress, Int32): Connects to a remote host using the specified IP address and port number
- ConnectAsync(IPAddress, Int32): Connects asynchronously
- BeginConnect(IPAddress, Int32, AsyncCallback, Object): Begins an asynchronous connection request
- GetStream(): Returns the NetworkStream used to send and receive data
- EndConnect(IAsyncResult): Ends a pending asynchronous connection attempt
- Close(): Disposes the TcpClient instance and closes the TCP connection
- Finalize(): Frees resources used by the TcpClient class
- Dispose(): Releases managed and unmanaged resources
Understanding Socket
Sockets in computer networks establish connections between computers for data transfer. A socket is a low-level access point to the IP stack and can be open, closed, or in intermediate states.
Sockets use IP addresses and network protocols to create secure communication channels.
Key Socket Properties:
- Available: Gets the amount of data received and available to be read.
- Connected: Indicates whether the Socket is connected to a remote host.
- Blocking: Gets or sets whether the Socket is in blocking mode.
- ReceiveBufferSize: Gets or sets the size of the receive buffer.
- SendTimeout: Gets or sets the send timeout.
Key Socket Methods:
- Accept(): Creates a new Socket for a newly created connection.
- Connect(IPAddress, Int32): Establishes a connection to a remote host.
- Listen(): Places a Socket in a listening state.
- SendFile(String): Sends a file to a connected Socket object.
- Send(Byte[]): Sends data to a connected Socket.
- Receive(Byte[]): Receives data from a bound Socket.
- Close(): Closes the Socket connection and releases resources.
- ReceiveTimeout : Gets or sets a value that specifies the amount of time after which a synchronous Receive call will time out
- SendBufferSize : Gets or sets a value that specifies the size of the send buffer of the Socket
TCP Services Demonstration
Development Steps:
- Create a Solution named DemoTCPService.
- Add two Console projects named ServerApp and ClientApp.
ServerApp Code
Contains methods ProcessMessage and ExecuteServer.
ClientApp Code
Contains method ConnectServer.
Working UDP Services
UDP provides a best-effort data delivery service without guarantees.
Applications must handle missing, duplicate, and out-of-sequence datagrams.
The UdpClient class abstracts details of creating a Socket for sending and receiving data using UDP.
UdpClient Class
Key Properties:
- Active: Gets or sets whether a default remote host has been established.
- Available: Gets the amount of data received and available to read.
- Client: Gets or sets the underlying network Socket.
Key Methods:
- Connect(String, Int32): Establishes a default remote host.
- Close(): Closes the UDP connection.
- Send(Byte[], Int32): Sends a UDP datagram to a remote host.
- Receive(IPEndPoint): Returns a UDP datagram from a remote host.
- JoinMulticastGroup(Int32, IPAddress): Adds a UdpClient to a multicast group.
- Dispose(): Releases resources.
UDP Services Demonstration
Development Steps:
- Create a Console project named UDPServerApp.
- Create a Console project named UDPClientApp.
UDPServerApp Code
Contains method StartListener.
UDPClientApp Code
Contains method ConnectServer.
Summary of Concepts
- Overview of Networking Basics
- Overview of Client-Server Model
- Explanation of URL, URN, and URI
- Explanation of WebRequest and WebResponse classes
- Explanation of HttpClient class
- Explanation of Domain Name System (DNS)
- Explanation of UDP service
- Overview of TCP Services: TcpListener, TcpClient, and Socket class
- Demonstration of WebRequest and HttpClient with .NET application
- Demonstration of TcpListener and TcpClient with .NET application
- Demonstration of UDP service with .NET application