Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Microsoft Visual C++ .NET Professional Projects - Premier Press

.pdf
Скачиваний:
180
Добавлен:
24.05.2014
Размер:
26 Мб
Скачать
☆

In this chapter, you will learn to develop a network-based application. But, before delving directly into creating the application, you need to understand the basic concepts involved in network programming, which is otherwise referred to as

socket programming.

Y To begin with, I will discuss the core conceptsLof socket programming and then

proceed to guide you through the processFof creating a network-based application. M Introducing NetworkA Programming E You probably spendTa lot of time each day sending and receiving e-mail, chatting,

and browsing the Web, all of which require communication between networked computers. Computers can communicate with each other only through the use of applications. For example, when you chat with someone, you use an application such as MSN Messenger. These applications are able to communicate with each other through network programming.

Communication between applications is similar to a telephone conversation. One application, say App1, establishes a connection with (calls) the application with which it wants to interact, say App2. But, how does App1 identify App2? Well, just as you need a telephone number to call another person, an application must know the location of the other application on the network. This is identified through the network address of the machine on which the application resides. Once the connection is established, the applications can interact with each other by passing messages. To end the interaction, the application has to disconnect and close the connection. Figure 29-1 illustrates this basic communication process.

In a telephonic conversation, both people implicitly follow certain rules: when one person talks the other listens, neither person talks continuously, and both don’t talk simultaneously. The same rules should be followed by applications that interact — you need to explicitly state the rules to both applications so that the interaction is carried off smoothly. These sets of rules are known as protocols.

Data travels in the form of packets from one machine to another on a network. Protocols govern the packaging of the data into packets, the speed of transmission,

Team-Fly®

IMPLEMENTING NETWORKING

Chapter 29

841

 

 

 

 

FIGURE 29-1 Interaction between applications

and the re-creation of data to its original form. Networking software usually implements multiple levels of protocols, layered one on top of another. Some wellknown network protocols are Transmission Control/Internet Protocol (TCP/IP), User Datagram Protocol (UDP), AppleTalk, and NetBEUI.

NOTE

In all network transactions, TCP/IP is the predominantly used protocol. UDP works like radio broadcasts.

You now know that for two applications to communicate, they need to establish a connection with each other and follow a protocol for smooth communication. How is this done? Objects called sockets enable you to implement network (or socket) programming.

The advantage of the socket model over other communication models is that the server is not affected by the source of client requests. It services all requests, and the clients are not restricted to any particular platform. They can be based on any platform, including UNIX, Windows, DOS, or Macintosh.

Because sockets form the basis of network programming, you need to have an indepth knowledge of them. So, I will next spend some time discussing sockets.

Sockets

In client/server applications, the server provides services such as processing database queries or modifying data in the database. The communication that occurs

842 Project 10 NETWORKING AND REMOTING IN VC++.NET

between the client and the server must be reliable. The data must not be lost and must be available to the client in the same sequence in which it was sent by the server.

TCP provides a reliable, point-to-point communication channel that client/server applications can use to communicate with each other. To communicate over TCP, client and server programs establish a connection and bind a socket. Sockets are used to handle communication links between applications over the network. Further, communication between the client and the server is through the socket. While talking about sockets, two other concepts that need to be discussed are IP addresses and ports. The next section introduces these two concepts.

IP Addresses and Ports

An Internet server can be thought of as a set of socket classes that provide additional capabilities — generally called services. Some examples of services are electronic mail, Telnet for remote login, and File Transfer Protocol (FTP) for transferring files across the network. Each service is associated with a port. A port is a numeric address through which service requests, such as a request for a Web page, are processed.

The TCP protocol requires two data items, the IP address and the port number. The Internet Protocol (IP) provides every network device with a logical address called an IP address. The IP addresses provided by the Internet Protocol take a specific form. Each address is a 32-bit number, represented as a series of four 8- bit numbers, which range in value from 0 to 255.

Since remembering numeric IP addresses is unrealistic, the IP addressing also allows you to assign names, such as microsoft.com. The Domain Name Service (DNS) is the service that translates such a name into its equivalent IP address.

Using IP addresses, you can trace the location of the computer on the network. Additionally, you need to specify the port through which you can establish your communication with the server. If you end up specifying a wrong address or phone number, the result would be that you get no connection or get connected to a wrong application.

However, if the port number is not specified, the server’s port in the services file is used. Every protocol has a default port number that is used if the port number is not specified. Table 29-1 lists the default port numbers used by applications.

 

IMPLEMENTING NETWORKING

Chapter 29

843

Table 29-1 Commonly Used Port Numbers

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Port Number

Description

 

 

 

 

 

 

 

 

 

 

21

FTP, which transfers files

 

 

 

 

23

Telnet, which provides a remote login

 

 

 

 

25

SMTP, which delivers mail messages

 

 

 

 

67

BOOTP, which provides configuration at boot time

 

 

 

 

80

HTTP, which transfers Web pages

 

 

 

 

109

POP, which enables users to access mailboxes on remote systems

 

 

 

 

 

 

Next, take a look at the different constituents of a network application. I will be discussing the different namespaces, classes, and methods that are involved in a VC++.NET-based network application.

Developing a Network Application by Using VC++.NET

To develop a network application, such as a chat application, by using VC++.NET, you need to have an idea of the different namespaces and classes involved. The following sections will give you a brief idea of the different namespaces and classes involved in developing the application.

The System.Net Namespace

The System.Net namespace consists of programming interfaces used by different protocols on the network. The WebRequest and WebResponse classes form the basis of protocols that can be reused across the network and enable you to use the resources on the Internet without worrying about the kind of protocol used.

The Socket Class

The Socket class is defined in the System.Net.Sockets namespace. It is responsible for creating and managing the communication between different ports on the network. To establish this communication, you need to create the socket and bind it to a specific endpoint by using the Bind method. Once the socket is bound,

844 Project 10 NETWORKING AND REMOTING IN VC++.NET

the connection to that endpoint is established using the Connect method. The Send and SendTo methods are used to send the data to the socket, and the Receive and ReceiveTo methods are used to receive the data from the socket. Once the task of sending and receiving is completed, you can use the Shutdown method to disable the socket or the Close method to close the socket.

The UdpClient and TcpClient classes, discussed next, use the Socket class to provide an Internet connection.

The UdpClient Class

The UdpClient class is a subclass of the Socket class and provides UDP services at a very high level of abstraction. UDP does not establish the connection with the remote host before sending and receiving the data. However, you can specify the default remote host by using any of the following methods:

Create an instance of the UdpClient class and call the Connect method.

Create an instance of the UdpClient class by specifying the remote host name and port number as parameters.

Use the Send and Receive methods to send and receive data from the remote host. To receive multicasted datagrams, use JoinMulticastGroup and DropMulticastGroup to connect and disconnect an UdpClient from a multicast group.

The following are the methods associated with UdpClient:

JoinMulticastGroup

Send

Receive

DropMulticastGroup

ToString

Close

The following sections give an overview of each of these methods.

The JoinMulticastGroup Method

The JoinMulticastGroup method is overloaded to add UdpClient to the multicast group. This method has two overloads:

IMPLEMENTING NETWORKING

Chapter 29

845

 

 

 

 

void JoinMulticastGroup(IPAddress *); void JoinMulticastGroup(IPAddress *,int);

Consider the following example:

void JoinMulticastGroup(IPAddress *groupaddress,int tl);

where groupaddress represents the IP address of the group you want to join, and tl is the value for Time-to-Live (TTL).

NOTE

The IP address for multicast packet ranges from 224.0.0.0 to 239.255.255.255.

TTL scopes the number of times a multicast can be forwarded by routers along a network.

The Send Method

The Send method is overloaded to send the UDP datagram to a remote host endpoint. The syntax of the method is

int send(unsigned char __gc[] data,int nobytes,IPEndPoint* endpt);

where,

data represents the array of bytes you want to send.

nobytes represents the number of bytes in the datagram.

endpt represents the host where you intend to send the datagram.

The Receive Method

The Receive method is used to return the UDP datagram sent by the remote host. The syntax of the method is

unsigned char Receive (IPEndPoint **rmtEP)__gc[];

where rmtEP represents the remote host from where the data was sent.

846 Project 10 NETWORKING AND REMOTING IN VC++.NET

The DropMulticastGroup Method

The DropMulticastGroup method is used to separate UdpClient from the multicast group. The syntax of the method is

void DropMulticastGroup(IPAddress* groupaddress);

where groupaddress represents the IP address of the multicast group.

The ToString Method

The ToString method returns the string representation of the object. The syntax of the method is

virtual String* ToString();

The following example illustrates the usage of the ToString method:

Object *obj = new Object();

String str=obj->ToString();

where obj represents the object.

The Close Method

The Close method is used to close the UDP connection. The syntax of the method is

void Close();

You have learned about the UDPClient class and some of its methods. Next, I will discuss the TcpClient class.

The TcpClient Class

The TcpClient class is a subclass of the Socket class and provides TCP services. The TcpClient class establishes the connection with the remote host, before sending and receiving the data, using any of the following methods:

Create an instance of the TcpClient class and call any of the Connect methods available.

Create an instance of the TcpClient class by specifying the remote host name and port number as constructor parameters.

IMPLEMENTING NETWORKING

Chapter 29

847

 

 

 

 

Use GetStream methods to obtain a NetworkStream that enables you to send data to and receive data from the Socket you are connected to. To extract data from and insert data in the Socket, use the Read and Write methods available in NetworkStream. Once the task of reading and writing is completed, you need to release all the resources associated with

TcpClient using the Close method.

The methods associated with TcpClient are discussed next.

The Connect Method

This method is overloaded to establish a connection between the TcpClient and remote TcpHost. This method has two overloads, listed here:

void Connect(IPAddress* addr,int port);

where addr signifies the IP address of the host you intend to connect to, and port signifies the port number you intend to connect.

void Connect(IPEndPoint* ipendpt);

where ipendpt signifies the IP endpoint to be connected.

The Equals Method

The Equals method is used to determine whether two instances of an object are equal. This method is overloaded and exists in two forms:

public: virtual bool Equals(Object*);

public: static bool Equals(Object*, Object*);

The GetStream Method

This method returns the stream that sends and receives the data. It creates an instance of the NetworkStream class that is used for network communication. The syntax of the method is as follows:

public: NetworkStream* GetStream();

The GetType Method

The GetType method returns the type of current instance of the object. If two objects have the same runtime type, the method will return true.

848 Project 10 NETWORKING AND REMOTING IN VC++.NET

The WebRequest Class

The WebRequest class is an abstract base class defined in the System.Net namespace. This class follows the .NET Framework’s request/response model to access data available on the Web.

Following are the steps for sending and receiving data using the Request and

Response classes:

1. Create an instance of the WebRequest class by using the

WebRequest.Create method.

2.Set the properties of the created instance. Sending and receiving of data is taken care of by the instance of the WebRequest class. However, if required, you can set the protocol-related properties by typecasting the instance of WebRequest.

3.To get the resource from the Internet, you need to call the GetResponse method of the WebRequest class.

4.To send the resource, you need to first upload the data to a resource using the Stream object and close the stream using the Stream.Close method.

5.Once the stream is closed, call the GetResponse method to ensure that the server receives correct data.

6.To get the stream containing data, call the GetResponseStream method of the WebResponse class. However, if required, you can set the protocolrelated properties by typecasting the instance of WebResponse.

7.Once you have completed reading the data from the response, close the response using the WebResponse.Close method.

The IPAddress Class

The IPAddress class is defined in the System.Net namespace. It provides an IP address of a computer on a particular network. The following code will create an instance of IPAddress:

IPAddress ipadr = IPAddress.Parse(“172.192.0.11”);

The methods associated with the IPAddress class are discussed next.

IMPLEMENTING NETWORKING

Chapter 29

849

 

 

 

 

The Equals Method

This method is overloaded to determine whether the two IP addresses are equal. The syntax for the method is as follows:

public override bool Equals(Object*);

The GetType Method

This method returns the type of current instance of the IPAddress class. If two objects have the same runtime type, the method will return true. The syntax is as follows:

public: Type* GetType();

The HostToNetworkOrder Method

This method is overloaded to convert the values from host byte order to network byte order. Every computer has it own way for ordering bytes. Some computers arrange the most significant bytes first, while some arrange the least significant bytes first. To enable computers using different byte orders to send the data on a network, the HostToNetworkOrder method is used. Table 29-2 lists the methods available for conversion of host byte to network byte for different data types.

Table 29-2 Methods for Conversion of Host Byte to Network Byte

Data Type

Methods

short

public: static short HostToNetworkOrder(short);

int

public: static int HostToNetworkOrder(int);

long

public: static int64 HostToNetworkOrder(int64);

 

 

The NetworkToHostOrder Method

This method is overloaded to convert the multibyte values on the host system from network byte order to host byte order. Table 29-3 lists the methods available for conversion of network byte to host byte for different data types.