Вы находитесь на странице: 1из 35

Networking in C#

C# is a language designed for the modern computing


environment, of which the Internet is, obviously, an important
part.
A main design criteria for C# was, therefore, to include those
features necessary for accessing the Internet.
Using standard features of C# and the .NET Framework, it is
easy to Internet-enable your applications and write other
types of Internet-based code.
Primary namespace for networking is System.Net. It defines a
large number of highlevel, 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.
Another important networking-related namespace is
System.Web. It supports ASP.NET-based network
applications.
System.Net
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.
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.
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 has the following simplified general form:
Protocol://HostName/FilePath?Query
Protocol specifies the protocol being used, such as HTTP.
HostName identifies a specific server, such as or
www.HerbSchildt.com.
FilePath specifies the path to a specific file.
Query specifies information that will be sent to the server. Query
is optional.
In C#, URIs are encapsulated by the Uri class.
Since WebRequest and WebResponse are main classes of
System.Net, they are discussed as:
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.
WebRequest defines no public constructors.
To send a request to a URI, you must first create an object of a class
derived from WebRequest that implements the desired protocol.
This can be done by calling Create( ), which is a static method
defined by WebRequest. Create( ) returns an object of a class that
inheritsWebRequest and implements a specific protocol.
Methods of WebRequest class
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 of WebResponse class
HttpWebRequest and HttpWebResponse
The classes HttpWebRequest and HttpWebResponse
inherit the WebRequest and WebResponse classes and
implement the HTTP protocol.
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("http://www.McGraw-Hill.com");
// Next, send that request and return the response.
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse();
// 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();
}}
resp.Close();
}}
The Uri Class
WebRequest.Create( ) has two different versions.
1. One accepts the URI as a string. This is the version used by
the preceding programs.
2. The other takes the URI as an instance of the Uri class,
which is defined in the System namespace.
The Uri class
encapsulates a URI. Using Uri, you can construct a URI that
can be passed to Create()
class UriDemo {
static void Main() {
Uri sample = new Uri("http://HerbSchildt.com/somefile.txt ");
Console.WriteLine("Host: " + sample.Host);
Console.WriteLine("Port: " + sample.Port);
Console.WriteLine("Scheme: " + sample.Scheme);
}
}
The output is shown here:
Host: HerbSchildt.com
Port: 80
Scheme: http
Local Path: /somefile.txt
Query: ?SomeQuery
Path and query: /somefile.txt?SomeQuery
Using WebClient
If your application only needs to upload or download data to
or from the Internet, then you can use WebClient.
Example
IPAddress Class
An IPAddress object is used to represent a single IP address.
This value can then be used in the various socket methods to
represent the IP address.
The default constructor for IPAddress is as follows:
public IPAddress(long address)
Some of the methods associated with IPAddress class are as
follows:
The Parse() method is most often used to create IPAddress
instances:
IPAddress newaddress = IPAddress.Parse("192.168.1.1");
This format allows you to use a standard dotted quad IP
address in string format and convert it to an IPAddress object.
The IPAddress class also provides four read-only fields that
represent special IP addresses for use in programs:
Any
Used to represent any IP address available on the local
system
Broadcast
Used to represent the IP broadcast address for the local
network
Loopback
Used to represent the loopback address of the system
None
Used to represent no network interface on the system
IPHostEntry hostDnsEntry = Dns.GetHostEntry("localhost");
foreach(IPAddress address in hostDnsEntry.AddressList)
{
Console.WriteLine("Type: {0}, Address: {1}",
address.AddressFamily, address);
}
//example console application 17
the me
thod used to obtain the local IP address:
IPHostEntry i =
Dns.GetHostByName(Dns.GetHostName());
IPAddress myself = i.AddressList[0];
using System;
using System.Net;
class AddressSample
{
public static void Main ()
{
IPAddress test1 = IPAddress.Parse("192.168.1.1");
IPAddress test2 = IPAddress.Loopback;
IPAddress test3 = IPAddress.Broadcast;
IPAddress test4 = IPAddress.Any;
IPAddress test5 = IPAddress.None;
IPHostEntry ihe =
Dns.GetHostByName(Dns.GetHostName());
IPAddress myself = ihe.AddressList[0];
if (IPAddress.IsLoopback(test2))
Console.WriteLine("The Loopback address is: {0}",
test2.ToString());
else
Console.WriteLine("Error obtaining the loopback address");
Console.WriteLine("The Local IP address is: {0}\n",
myself.ToString());
}
}
} /// window application 18
Socket
A socket is one endpoint of a two-way communication link
between two programs running on the network. A socket is
bound to a port number so that the TCP layer can identify the
application that data is destined to be sent.
An endpoint is a combination of an IP address and a port
number. Every TCP connection can be uniquely identified by
its two endpoints. That way you can have multiple connections
between your host and the server.
Sockets are the fundamental technology for programming
software to communicate on TCP/IP networks. A socket
provides a bidirectional communication endpoint for sending
and receiving data with another socket. Socket connections
normally run between two different computers on a LAN or
across the Internet, but they can also be used for inter-process
communication on a single computer.
The socket defines the following:
A specific communication domain, such as a network
connection
Aspecific communication type, such as stream or datagram
Aspecific protocol, such as TCP or UDP
After the socket is created, it must be bound to either a specific
network address and port on the system, or to a remote network
address and port. Once the socket is bound, it can be used to
send and receive data from the network.
The following example creates a Socket that can be used to
communicate on a TCP/IP-based network, such as the Internet.
Socket s = new Socket(AddressFamily.I nterNetwork,
SocketType.Stream, ProtocolType.Tcp);
the AddressFamily.InterNetwork member specifies the IP
version 4 address family).
ProtocolType.Tcp indicates that the socket uses
TCP; ProtocolType.Udp indicates that the socket uses UDP).
SocketType.Stream member indicates a standard socket for
sending and receiving data with flow control).
in .NET, there is a class under System.Net namespace
called IPEndPoint, which represents a network
computer as an IP address and a port number.
public IPEndPoint(System.Net.IPAddress address,
int port);
you can send data to the other side using
the Send method of the Socket class.
Try
{
String s= "I am here";
byte[] byData = System.Text.Encoding.ASCII.GetBytes(s);
m_socClient.Send(byData);
}
catch (SocketException se)
{
MessageBox.Show ( se.Message );
}
Similar to Send, there is a Receive method on
the Socket class. You can receive data using the
following call:
byte [] buffer = new byte[1024];
int i = m_socClient.Receive (buffer);
Listen causes a connection-oriented Socket to listen for
incoming connection attempts. The backlogparameter specifies
the number of incoming connections that can be queued for
acceptance. To determine the maximum number of
connections you can specify, retrieve the MaxConnections
value.
Socket listenSocket = new
Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(hostIP, port);
listenSocket.Bind(ep);
listenSocket.Listen(backlog);
Accept synchronously extracts the first pending connection
request from the connection request queue of the listening
socket, and then creates and returns a new Socket.
protected void AcceptMethod(Socket listeningSocket)
{
Socket mySocket = listeningSocket.Accept();
}

Вам также может понравиться