Download presentation
Presentation is loading. Please wait.
1
Visual Programming COMP-315
Chapter #7 Network Programming
2
Networking support is contained in several namespaces defined by the
Networking support is contained in several namespaces defined by the .NET Framework. The primary namespace for networking is System.Net. It defines a large number of high-level, easy-to-use classes that support the various types of operations common to the Internet. Several namespaces nested under System.Net are also provided. For example, low-level networking control through sockets is found in System.Net.Sockets. Mail support is found in System.Net.Mail. Support for secure network streams is found in System.Net.Security. Several other nested namespaces provide additional functionality. Another important networking-related namespace is System.Web. It (and its nested namespaces) support ASP.NET-based network applications.
3
Although System.Net defines many members, only a few are needed to accomplish most common Internet programming tasks. At the core of networking are the abstract classes WebRequest and WebResponse. These classes are inherited by classes that support a specific network protocol. (A protocol defines the rules used to send information over a network.) For example, the derived classes that support the standard HTTP protocol are HttpWebRequest and HttpWebResponse. Even though WebRequest and WebResponse are easy to use, for some tasks you can employ an even simpler approach based on WebClient. For example, if you only need to upload or download a file, then WebClient is often the best way to accomplish it.
4
Uniform Resource Identifiers :
Fundamental to Internet programming is the Uniform Resource Identifier (URI). A URI describes the location of some resource on the network. A URI is also commonly called a URL, which is short for Uniform Resource Locator.
5
Internet Access Fundamentals
The hierarchy of classes topped by WebRequest and WebResponse implement what Microsoft calls pluggable protocols. There are several different types of network communication protocols. The most common for Internet use is HyperText Transfer Protocol (HTTP). Another is File Transfer Protocol (FTP). When a URI is constructed, the prefix of the URI specifies the protocol. For example, uses the prefix http, which specifies hypertext transfer protocol. The classes that support HTTP are HttpWebRequest and HttpWebResponse. These classes inherit WebRequest and WebResponse and add several members of their own, which apply to the HTTP protocol.
6
synchronous and asynchronous communication.
System.Net supports both synchronous and asynchronous communication. For many Internet uses, synchronous transactions are the best choice because they are easy to use. With synchronous communications, your program sends a request and then waits until the response is received. For some types of high-performance applications, asynchronous communication is better. Using the asynchronous approach, your program can continue processing while waiting for information to be transferred.
7
WebRequest TheWebRequest class manages a network request. It is abstract because it does not implement a specific protocol. It does, however, define those methods and properties common to all requests. Methods: public static WebRequest Create(string uri) Creates a WebRequest object for the URI specified by the string passed by uri public static WebRequest Create(Uri uri) Creates a WebRequest object for the URI specified by uri public virtual Stream GetRequestStream( ) Returns an output stream associated with the previously requested URI public virtual WebResponse GetResponse( ) Sends the previously created request and waits for a response.
8
WebResponse WebResponse encapsulates a response that is obtained as the result of a request. WebResponse is an abstract class. Inheriting classes create specific, concrete versions of it that support a protocol. A WebResponse object is normally obtained by calling the GetResponse( ) method defined by WebRequest. This object will be an instance of a concrete class derived from WebResponse that implements a specific protocol. Methods: public virtual void Close( ) Closes the response. It also closes the response stream returned by GetResponseStream( ) public virtual Stream GetResponseStream( ) Returns an input stream connected to the requested URI. Using this stream, data can be read from the URI
9
HttpWebRequest & HttpWebResponse
The classes HttpWebRequest and HttpWebResponse inherit the WebRequest and WebResponse classes and implement the HTTP protocol. In the process, both add several properties that give you detailed information about an HTTP transaction.
10
Example Program The program displays the hypertext on the screen in chunks of 400 characters, so you can see what is being received before it scrolls off the screen. // Access a website. using System; using System.Net; using System.IO; class NetDemo { static void Main() { int ch; // First, create a WebRequest to a URI. HttpWebRequest req = (HttpWebRequest) WebRequest.Create(" // Next, send that request and return the response. HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
11
Continued // From the response, obtain an input stream. Stream istrm = resp.GetResponseStream(); /* Now, read and display the html present at the specified URI. So you can see what is being displayed, the data is shown 400 characters at a time. After each 400 characters are displayed, you must press ENTER to get the next 400. */ for(int i=1; ; i++) { ch = istrm.ReadByte(); if(ch == -1) break; Console.Write((char) ch); if((i%400)==0) { Console.Write("\nPress Enter."); Console.ReadLine(); } // Close the response. This also closes istrm. resp.Close(); } }
12
Handling Network Errors
Although the program in the preceding slide is correct, it is not resilient. Even the simplest network error will cause it to end abruptly. To fully handle all network exceptions that the program might generate, you must monitor calls to Create( ), GetResponse( ), and GetResponseStream( ). Exceptions Generated by Create( ): The Create( ) method defined by WebRequest can generate four exceptions. NotSupportedException UriFormatException System.Security.SecurityException ArgumentNullException
13
Handling Network Errors Cont.
Exceptions Generated by GetReponse( ) : The Create( ) method defined by WebRequest can generate four exceptions. InvalidOperationException ProtocolViolationException NotSupportedException WebException
14
Accessing Cookies You can gain access to the cookies associated with an HTTP response through the Cookies property defined by HttpWebResponse. Cookies contain information that is stored by a browser. They consist of name/value pairs, and they facilitate certain types of web access. The Cookies property is defined like this: public CookieCollection Cookies { get; set; }
15
.NET Networking Namespaces
System.Threading System.Net System.Net.Sockets System.Runtime.Remoting
16
System.Threading Provides classes that enable multi-threaded programming Synchronize mutually-exclusive threads Manage groups of threads Enable timing
17
System.Threading Primary Classes
Monitor, Mutex : Provides the synchronization of threading objects using locks and wait/signals _ ReaderWriterLock : Defines the lock that implements single-writer and multiple-reader semantics _ Thread : Represents threads that execute within the runtime to create and control threads _
18
System.Threading Primary Classes
ThreadPool : Posts work items to the thread pool and queues work items for execution on the first available thread from the thread pool Timeout : Contains timeout value for methods
19
System.Net Provides a simple programming interface to
Many of the protocols found on the network today An implementation of network services that enables you to develop applications that use Internet resources
20
System.Net Primary Classes
Dns : Provides simple domain name resolution functionality SocketAddress : Identifies a socket address IPAddress : Provides an Internet Protocol (IP) address DnsPermission : Controls rights to access Domain Name System (DNS) servers on the network
21
System.Net Primary Classes (cnt.)
NetworkCredential : Credentials for password-based authentication schemes HttpWebRequest, HttpWebResponse : HTTP implementation of request and response objects WebClient : Provides common methods for sending data to and receiving data from a resource identified by a URI
22
System.Net.Sockets Provides
A managed implementation of the Windows Sockets interface for developers that need to tightly control access to the network Encapsulations for TCP and UDP clients and listeners
23
System.Net.Sockets Primary Classes
MulticastOption : Contains IP address values for IP multicast packets _ Socket : Implements the Berkeley sockets interface _ TCPClient, TCPListener : Provides client connections and listeners for TCP network _ UDPClient : Provides UDP network services _
24
.NET Socket Programming Example
Multicast Group UDP Chat Client Send Msg Recieve Msg
25
MulticastOption [C#] public class MulticastOption Sets IP address values when joining or leaving an IP multicast group. Example: [C#] Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ); sock.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption( groupIP ));
26
Socket [C#] public class Socket : IDisposable The Socket class creates a managed version of an Internet transport service. Primary methods: Bind, Connect, Send, SendTo, Recieve, RecieveFrom, Shutdown, Close. Example: [C#] IPAddress hostadd = Dns.Resolve(server).AddressList[0]; IPEndPoint EPhost = new IPEndPoint(hostadd, 80); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); s.Connect(EPhost); s.Send(ByteGet, ByteGet.Length, 0);
27
TCPClient [C#] public class TcpClient : Idisposable The TcpClient class builds upon the Socket class to provide TCP services at a higher level of abstraction. Example: [C#] // Connect to a TCP Server TcpClient myClient = new TcpClient("time.contoso.com",13); // Get the response stream Stream myStream = myClient.GetStream();
28
TCPListener [C#] public class TcpListener The TcpListener class builds upon the Socket class to provide TCP services at a higher level of abstraction. Example: [C#] TcpListener myListener = new TcpListener(13); myListener.Start(); // Program blocks on Accept() until a client connects. Socket mySocket = myListener.AcceptSocket();
29
UDPClient [C#] public class UdpClient : IDisposable The UdpClient class provides access to UDP services at a higher level of abstraction than the Socket class does. UdpClient connects to remote hosts and receives connections from remote clients.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.