This document provides an overview of networking programming concepts in .NET, including: - Client-server model and networking basics like IP addresses and ports - Classes for HTTP requests (WebRequest, WebResponse) and REST calls (HttpClient) - TCP networking with TcpListener and TcpClient classes - Domain Name System (DNS) and its role in resolving domain names - Code demonstrations of making HTTP requests and setting up a TCP listener/client The document aims to explain the key concepts and classes for developing network applications in .NET.
Introduces Networking Programming, client-server models, and various classes like WebRequest, WebResponse, and HttpClient.
Discusses the significance of learning networking to develop distributed applications that operate over local and wide area networks.
Defines key networking concepts such as clients, servers, IP addresses (IPv4, IPv6), ports, and protocols (TCP, UDP).
Explains the client-server communication model and how to distinguish computers and processes using IP addresses and hostnames.
Describes URIs, with a focus on differences between URLs and URNs, including examples and their structural elements.
Overview of the System.Net namespaces and classes for network communication including WebClient, HttpClient, and DNS functionalities.
Explains the WebRequest class' role in HTTP requests, its properties, methods, and how it handles data retrieval.
Describes the WebResponse class used to handle server responses, including key properties and methods for data access.
Explains HttpClient's functionality as a superior alternative to WebClient for handling HTTP requests and responses.
Demonstrates the use of HttpClient in a WPF application, including UI setup and event handling for fetching web content.
Explains how DNS translates domain names to IP addresses and its components, such as name servers and resolvers.
Overview of the System.Net.Sockets namespace and classes like TcpClient and TcpListener utilized for TCP service.Describes TCP services structure, how TcpListener and TcpClient work for establishing and managing TCP connections.
Explains the concept of sockets, their role in data communication, and provides details on Socket class methods and properties.
Provides a step-by-step guide for creating a TCP client-server application using .NET.
Introduces User Datagram Protocol (UDP), its characteristics, and how the UdpClient class works for communication.
Guides on creating and running a UDP client-server application demonstrating the use of UDP protocol.
Summarizes the key concepts discussed, including client-server models, HTTP classes, and DNS.
2 Overview NetworkingBasic Overview Client-Server Model Explain about URL, URN and URI Explain about WebRequest and WebResponse class Explain about HttpClient class Explain about Domain Name System (DNS) Overview TCP Services: TcpListener, TcpClient and Socket class Demo WebRequest and HttpClient with .NET application Demo TcpListener and TcpClient with .NET application Explain and demo about UDP service with .NET application 7/21/2022 Objectives
3.
7/21/2022 3 Why ShouldWe Study This Lecture? Nowadays, distributed applications are popular. People need large applications, running based on a computer network (local area networks-LANs- or wide area network-WAN), including many sites working concurrently. Do you want to create such applications? How do we develop network applications by .NET?
7/21/2022 5 Platform:Hardware + Operating system Client: an application running in a computer (such as browser) can receive data from another (server) Server: an application running in a computer (such as IIS- Windows Internet Information Service, Kestrel, Nginx) can supply data to others (clients) IP address (Internet Protocol): unsigned integer helps identifying a network element(computer, router,…) IPv4: 4-byte IP address, such as 192.143.5.1 IPv6: 16-byte IP address Port: unsigned 2-byte integer helps operating system differentiating a network communicating process Some Definitions Related to Networking
6.
7/21/2022 6 Some DefinitionsRelated to Networking Protocol: Rules for packaging data of a network communication because client and server can be working in different platform. Two common basic protocols are TCP and UDP TCP: (Transmission Control Protocol) is a connection-based protocol (only one connecting line only) that provides a reliable flow of data between two computers based on the acknowledge mechanism UDP: (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival (many connecting lines can be used, acknowledge mechanism is not used). Many firewalls and routers have been configured not to allow UDP packets. Ask our system administrator if UDP is permitted
7/21/2022 9 Howto distinguish a computer in a network? Client-Server Model IP:152.3.21.121 or Hostname Personal computer IP: 127.0.0.1 An IP address is either a 32-bit or 128-bit unsigned number used by IP, a lower-level protocol on which protocols like UDP and TCP are built. The IP address architecture is defined by RFC 790
10.
7/21/2022 10 Howto distinguish a network-communicating process in a computer? Client-Server Model
11.
7/21/2022 11 AURI (Uniform Resource Identifier) is a specially formatted string that describes a resource on the internet or a LAN, such as a web page, file, or email address A URI can be broken up into a series of elements—typically, scheme, authority, and path The Uri class in the System namespace performs just this division, exposing a property for each element URI properties URL, URN and URI
12.
7/21/2022 12 URL, URNand URI URL stands for Uniform Resource Location. URL is a subset of URI that describes the network address or location where the source is available URL begins with the name of the protocol to be used for accessing the resource and then specific resource location
13.
7/21/2022 13 URLsbuild on the Domain Name Service (DNS) to address hosts symbolically and use a file-path like syntax to identify specific resources at a given host. For this reason, mapping URLs to physical resources is straightforward and is implemented by various Web browsers URN stands for Uniform Resource Name. It is a URI that uses a URN scheme “urn” scheme: It is followed by a namespace identifier, followed by a colon, followed by namespace specific string. For example : urn:isbn:0451450523 URN does not imply the availability of the identified resource.URNs are location- independent resource identifiers and are designed to make it easy to map other namespaces into URN space URL, URN and URI
7/21/2022 16 Understanding System.Net.*Namespaces The .NET offers a variety of classes in the System.Net.* namespaces for communicating via standard network protocols, such as HTTP, TCP/IP, and FTP. The summary key components as follows : A WebClient 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 consuming HTTP web APIs and RESTful services HttpListener for writing an HTTP server SmtpClient for constructing and sending mail messages via SMTP Dns for converting between domain names and addresses TcpClient, UdpClient, TcpListener, and Socket classes for direct access to the transport and network layers
7/21/2022 18 Understanding WebRequestClass WebRequest and WebResponse are common base classes for managing both HTTP and FTP client-side activity as well as the “file:” protocol. They encapsulate the request/response model that these protocols all share: the client makes a request, and then awaits a response from a server WebRequest is the abstract base class for .NET's request/response model for accessing data from the Internet An application that uses the request/response model can request data from the Internet in a protocol-agnostic manner, in which the application works with instances of the WebRequest class while protocol-specific descendant classes carry out the details of the request
19.
7/21/2022 19 Understanding WebRequestClass Property Name Description ContentLength When overridden in a descendant class, gets or sets the content length of the request data being sent ContentType When overridden in a descendant class, gets or sets the content type of the request data being sent Credentials When overridden in a descendant class, gets or sets the network credentials used for authenticating the request with the Internet resource Method When overridden in a descendant class, gets or sets the protocol method to use in this request Headers When overridden in a descendant class, gets or sets the collection of header name/value pairs associated with the request RequestUri When overridden in a descendant class, gets the URI of the Internet resource associated with the request Timeout Gets or sets the length of time, in milliseconds, before the request times out The following table describes some of the key properties:
20.
7/21/2022 20 Understanding WebRequestClass Method Name Description Create(Uri) Initializes a new WebRequest instance for the specified URI scheme GetRequestStream() When overridden in a descendant class, returns a Stream for writing data to the Internet resource GetResponse() When overridden in a descendant class, returns a response to an Internet request CreateHttp(String) Initializes a new HttpWebRequest instance for the specified URI string BeginGetRequestStream(AsyncCallback, Object) When overridden in a descendant class, provides an asynchronous version of the GetRequestStream() method BeginGetResponse(AsyncCallback, Object) When overridden in a descendant class, begins an asynchronous request for an Internet resource Abort() Aborts the request The following table describes some of the key methods:
21.
7/21/2022 21 Understanding WebResponseClass The WebResponse class is the abstract base class from which protocol- specific response classes are derived Applications can participate in request and response transactions in a protocol- agnostic manner using instances of the WebResponse class while protocol- specific classes derived from WebResponse carry out the details of the request Client applications do not create WebResponse objects directly, they are created by calling the GetResponse method on a WebRequest instance
22.
7/21/2022 22 Understanding WebResponseClass Property Name Description ContentLength When overridden in a descendant class, gets or sets the content length of data being received ContentType When overridden in a derived class, gets or sets the content type of the data being received Headers When overridden in a derived class, gets a collection of header name-value pairs associated with this request IsFromCache Gets a Boolean value that indicates whether this response was obtained from the cache Method Name Close() When overridden by a descendant class, closes the response stream GetResponseStream() When overridden in a descendant class, returns the data stream from the Internet resource The following table describes some of the key properties and methods:
7/21/2022 24 Understanding HttpClientClass HttpClient provides another layer on top of HttpWebRequest and HttpWeb Response HttpClient was written in response to the growth of HTTP-based web APIs and REST services to provide a better experience than WebClient class ( WebClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI ) when dealing with protocols more elaborate than simply fetching a web page HttpClient is a newer API for working with HTTP and is designed to work 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
25.
7/21/2022 25 Understanding HttpClientClass An HttpClient instance is a collection of settings applied to all requests executed by that instance. In addition, every HttpClient instance uses its own connection pool, isolating its requests from requests executed by other HttpClient instances HttpClient has a richer and extensible type system for headers and content HttpClient lets us write and plug in custom message handlers. This enables mocking in unit tests, and the creation of custom pipelines (for logging, compression, encryption, and so on)
26.
7/21/2022 26 Understanding HttpClientClass Property Name Description BaseAddress Gets or sets the base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests MaxResponseContentBufferSize Gets or sets the maximum number of bytes to buffer when reading the response content Timeout Gets or sets the timespan to wait before the request times out Method Name GetAsync(String) Send a GET request to the specified Uri as an asynchronous operation GetStringAsync(String) Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation PostAsync(String, HttpContent) Send a POST request to the specified Uri as an asynchronous operation PutAsync(String, HttpContent) Send a PUT request to the specified Uri as an asynchronous operation DeleteAsync(String) Send a DELETE request to the specified Uri as an asynchronous operation The following table describes some of the key properties and methods:
7/21/2022 32 2.Write codesin MainWindow.xaml.cs and run the project as follows: //… using System.Net.Http;
33.
7/21/2022 33 Understanding DomainName System (DNS) Domain Name System (DNS) is the process , which converts Internet address in mnemonic form into the equivalent number IP address DNS can also be considered as an database that is present on various computers and has names and IP address of various hosts on the internet The DNS consists of three components: The first is a “Name Space” that establishes the syntactical rules for creating and structuring legal DNS names The second is a “Globally Distributed Database” implemented on a network of “Name Servers” The third is "Resolver" software, which understands how to formulate a DNS query and is built into practically every Internet-capable application
7/21/2022 35 The System.Net.SocketsNamespace Provides a managed implementation of the Windows Sockets (Winsock) interface for developers who need to tightly control access to the network Class Name Description Socket Implements the Berkeley sockets interface TcpClient Provides client connections for TCP network services TcpListener Listens for connections from TCP network clients UdpClient Provides User Datagram Protocol (UDP) network services NetworkStream Provides the underlying stream of data for network access SocketAsyncEventArgs Represents an asynchronous socket operation SocketException The exception that is thrown when a socket error occurs SocketTaskExtensions This class contains extension methods to the Socket class The following table describes some of the key classes:
36.
7/21/2022 36 Working TCPServices The Tranmission Control Protocol (TCP) services contain classes and methods for connecting and sending data between two points or more points. A point consists of both an IP (Internet Protocol) and port number The TcpClient and TcpListener classes create the TCP connections on the internet and contain methods and properties for connecting, sending and receiving stream data over the network
37.
7/21/2022 37 The TcpListenerClass The TcpListener class provides simple methods that listen for and accept incoming connection requests in blocking synchronous mode. We can use either a TcpClient or a Socket to connect with a TcpListener The following table describes some of the key methods: Method Name Description AcceptSocket() Accepts a pending connection request AcceptSocketAsync() Accepts a pending connection request as an asynchronous operation AcceptTcpClient() Accepts a pending connection request AcceptTcpClientAsync() Accepts a pending connection request as an asynchronous operation Start() Starts listening for incoming connection requests Stop() Closes the listener Pending() Determines if there are pending connection requests
38.
7/21/2022 38 The TcpClientClass The TcpClient class provides simple methods for connecting, sending, and receiving stream data over a network in synchronous blocking mode In order for TcpClient to connect and exchange data, a TcpListener or Socket created with the TCP ProtocolType must be listening for incoming connection requests. We can connect to this listener in one of the following two ways: Create a TcpClient and call one of the three available Connect methods Create a TcpClient using the host name and port number of the remote host. This constructor will automatically attempt a connection
39.
7/21/2022 39 The TcpClientClass The following table describes some of the key properties: Property Name Description Active Gets or sets a value that indicates whether a connection has been made Available Gets the amount of data that has been received from the network and is available to be read Client Gets or sets the underlying Socket Connected Gets a value indicating whether the underlying Socket for a TcpClient is connected to a remote host ReceiveBufferSize Gets or sets the size of the receive buffer ReceiveTimeout Gets or sets the amount of time a TcpClient will wait to receive data once a read operation is initiated SendBufferSize Gets or sets the size of the send buffer SendTimeout Gets or sets the amount of time a TcpClient will wait for a send operation to complete successfully ReceiveBufferSize Gets or sets the size of the receive buffer
40.
7/21/2022 40 The TcpClientClass The following table describes some of the key methods: Method Name Description Connect(IPAddress, Int32) Connects the client to a remote TCP host using the specified IP address and port number ConnectAsync(IPAddress, Int32) Connects the client to a remote TCP host using the specified IP address and port number as an asynchronous operation BeginConnect(IPAddress, Int32, AsyncCallback, Object) Begins an asynchronous request for a remote host connection. The remote host is specified by an IPAddress and a port number (Int32) GetStream() Returns the NetworkStream used to send and receive data EndConnect(IAsyncResult) Ends a pending asynchronous connection attempt Close() Disposes this TcpClient instance and requests that the underlying TCP connection be closed Finalize() Frees resources used by the TcpClient class Dispose() Releases the managed and unmanaged resources used by the TcpClient
41.
7/21/2022 41 Socketsin computer networks are used to establish a connection between two or more computers and used to send data from one computer to another. Each computer in the network is called a node A socket is an object that represents a low-level access point to the IP stack. This socket can be open or closed or one of a set number of intermediate states Sockets use nodes’ IP addresses and a network protocol to create a secure channel of communication and use this channel to transfer data Understanding Socket
42.
7/21/2022 42 The SocketClass Property Name Description Available Gets the amount of data that has been received from the network and is available to be read Connected Gets a value that indicates whether a Socket is connected to a remote host as of the last Send or Receive operation Blocking Gets or sets a value that indicates whether the Socket is in blocking mode. ReceiveBufferSize Gets or sets a value that specifies the size of the receive buffer of the Socket SendTimeout Gets or sets a value that specifies the amount of time after which a synchronous Send call will time out The Socket class provides a rich set of methods and properties for network communications The Socket class allows us to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the ProtocolType enumeration. The following table describes some of the key properties and methods:
43.
7/21/2022 43 The SocketClass Method Name Description Accept() Creates a new Socket for a newly created connection Connect(IPAddress, Int32) Establishes a connection to a remote host. The host is specified by an IP address and a port number Listen() Places a Socket in a listening state SendFile(String) Sends the file fileName to a connected Socket object with the UseDefaultWorkerThread transmit flag Send(Byte[]) Sends data to a connected Socket Receive(Byte[]) Receives data from a bound Socket into a receive buffer Close() Closes the Socket connection and releases all associated resources Property Name Description 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
7/21/2022 45 How dowe develop? 1. Create a Solution named DemoTCPService 2. Addition to this solution two Console projects named ServerApp and ClientApp
46.
7/21/2022 46 3. Writecodes in Program.cs of the ServerApp as follows : View details in next slide
7/21/2022 52 6. Right-clickon the ClientApp project, select Set as Startup Project then press Ctrl+F5 to run it
53.
7/21/2022 53 Working UDPServices User Datagram Protocol (UDP) is a simple protocol that makes a best effort to deliver data to a remote host The UDP protocol is connectionless protocol thus UDP datagrams sent to the remote endpoint are not guaranteed to arrive and they aren’t guaranteed to arrive in the same sequence in which they are sent. Applications that use UDP must be prepared to handle missing, duplicate, and out-of-sequence datagrams The UdpClient class communicates with network services using UDP. The properties and methods of the UdpClient class abstract the details of creating a Socket for requesting and receiving data using UDP
54.
7/21/2022 54 UdpClient Class The following table describes some of the key properties and methods: Property Name Description Active Gets or sets a value indicating whether a default remote host has been established Available Gets the amount of data received from the network that is available to read Client Gets or sets the underlying network Socket Method Name Description Connect(String, Int32) Establishes a default remote host using the specified host name and port number Close() Closes the UDP connection Send(Byte[], Int32) Sends a UDP datagram to a remote host Receive(IPEndPoint) Returns a UDP datagram that was sent by a remote host JoinMulticastGroup(Int32, IPAddress) Adds a UdpClient to a multicast group Dispose() Releases the managed and unmanaged resources used by the UdpClient
7/21/2022 56 1. Createa Console project named UDPServerApp then write codes in Program.cs as follows :
57.
7/21/2022 57 2. Createa Console project named UDPClientApp then write codes in Program.cs as follows :
58.
7/21/2022 58 3. Right-clickon the UDPServerApp project, select Set as Startup Project then press Ctrl+F5 to run it
59.
7/21/2022 59 4. Right-clickon the UDPClientApp project, select Set as Startup Project then press Ctrl+F5 to run it
60.
Summary Concepts wereintroduced: Overview Networking Basic Overview Client-Server Model Explain about URL, URN and URI Explain about WebRequest and WebResponse class Explain about HttpClient class Explain about Domain Name System (DNS) Explain about UDP service Overview TCP Services: TcpListener, TcpClient and Socket class Demo WebRequest and HttpClient with .NET application Demo TcpListener and TcpClient with .NET application Demo UDP service with .NET application 60