Use. NET access to the Internet (3) Paul

Source: Internet
Author: User
Tags add time bool command line getstream connect socket tostring port number
Use. NET access to the Internet (3) Paul_ni (original)

author : China Information Network source : zixuen.com Add time : 2005-5-12 www.zixuen.com

Using the TCP service


The TcpClient class uses TCP to request data from Internet resources.TcpClientMethod and property to extract the creation details of a Socket instance that is used to request and receive data over TCP. Because a connection to a remote device is represented as a stream, you can use the. NET Framework streaming technology to read and write data.
The TCP protocol establishes a connection to a remote endpoint and then uses this connection to send and receive packets. TCP is responsible for ensuring that packets are sent to endpoints and that they are grouped in the correct order when the packets arrive.
To establish a TCP connection, you must know the address of the network device that hosts the required services and the TCP port that the service uses for communication. The Internet Allocation number Authority (Internet assigned Numbers Authority, IANA) defines the port number of the public service (see Http://www.iana.org/assignments/port-numbers). Services that are not in the IANA list can use the port number in the range 1,024 through 65,535.
The following code shows how to set theTcpClientTo connect to a time server on TCP Port 13.
[C #]
Using System;
Using System.Net.Sockets;
Using System.Text;

public class Tcptimeclient {
Private Const int portnum = 13;
Private Const string hostName = "host.contoso.com";

public static int Main (string[] args) {
try {
TcpClient client = new TcpClient (HostName, portnum);

NetworkStream ns = client. GetStream ();

byte[] bytes = new byte[1024];
int bytesread = ns. Read (bytes, 0, bytes. Length);

Console.WriteLine (Encoding.ASCII.GetString (Bytes,0,bytesread));

Client. Close ();

catch (Exception e) {
Console.WriteLine (E.tostring ());
}

return 0;
}
}
TcpListener is used to monitor incoming requests on TCP ports and then createSocketOrTcpClientInstance to manage the connection to the client. The Start method enables listening, and the Stop method disables listening on the port. The AcceptTcpClient method accepts incoming connection requests and createsTcpClientTo process the request, the AcceptSocket method accepts incoming connection requests and createsSocketTo process the request.
The following code shows how to use theTcpListenerCreate a network time server to monitor TCP Port 13. When an incoming connection request is accepted, the time server responds with the current date and time from the host server.
[C #]
Using System;
Using System.Net.Sockets;
Using System.Text;

public class Tcptimeserver {

Private Const int portnum = 13;

public static int Main (string[] args) {
bool done = false;

TcpListener listener = new TcpListener (portnum);

Listener. Start ();

while (!done) {
Console.Write ("Waiting for Connection ...");
TcpClient client = listener. AcceptTcpClient ();

Console.WriteLine ("Connection accepted.");
NetworkStream ns = client. GetStream ();

byte[] Bytetime = Encoding.ASCII.GetBytes (DateTime.Now.ToString ());

try {
Ns. Write (bytetime, 0, bytetime.length);
Ns. Close ();
Client. Close ();
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}

Listener. Stop ();

return 0;
}

}

Using UDP Services


The UdpClient class uses UDP to communicate with network services.UdpClientClass to extract the creation details of a Socket instance, which is used to request and receive data through UDP.
The advantage of UDP is its ease of use and the ability to broadcast messages to multiple addresses at the same time. However, because the UDP protocol is a connectionless protocol, UDP datagrams sent to remote endpoints are not necessarily reachable or can be reached in the same order in which they were sent. Applications that use UDP must be prepared to handle lost and incorrectly sequenced datagrams.
To send datagrams using UDP, you must know the network address of the network device that hosts the required services and the UDP port number that the service uses for communication. The Internet Allocation number Authority (Internet assigned Numbers Authority, IANA) defines the port number of the public service (see Http://www.iana.org/assignments/port-number s). Services that are not in the IANA list can use the port number in the range 1,024 through 65,535.
Special network addresses are used to support UDP broadcast messages on ip-based networks. The following discussion is an example of the IP version 4 address family used on the Internet.
The IP version 4 address uses 32-bit to specify the network address. For class C addresses that use the 255.255.255.0 netmask, these bits are divided into four eight-bit bytes. When expressed as a decimal number, these four eight-bit bytes form a familiar, dotted, four-part representation, such as 192.168.100.2. The first two eight-bit bytes (192.168 in this example) Form the network number, the third eight-bit byte (100) defines the subnet, and the last eight-bit byte (2) is the host identifier.
Setting all the bits of an IP address to 1 (that is, 255.255.255.255) can constitute a limited broadcast address. Sending a UDP datagram to this address delivers a message to any host on that broadcast network. Because routers never forward messages that are sent to this address, only hosts on connected networks can see these broadcasts.
You can direct a broadcast to a specific network section by setting all the bits in a part of the address to 1. For example, to send a broadcast to all hosts on a network identified by a 192.168 IP address, set the subnet and host portions of the address to 1, such as 192.168.255.255. To limit broadcasts to a single subnet, only the host portion is set to 1, such as 192.168.100.255.
UdpClientClass can broadcast to any network broadcast address, but it cannot listen to broadcasts that are sent to the network. Must useSocketclass to listen for webcasts.
Broadcast addresses work when all recipients are in a single network, or when many clients need to receive broadcasts. When the receiver is a small part of the network, the message should be sent to the multicast group, where only clients joining this group can receive the message. The range of IP addresses from 224.0.0.2 to 244.255.255.255 is reserved for the primary group address. The IP number 224.0.0.0 is reserved, and the 224.0.0.1 is assigned to a fixed group of all IP hosts.
The following example uses theUdpClientListens to UDP datagram broadcasts for multicast address groups on port 11000 224.168.100.2. It receives the message string and writes the message to the console.
[C #]
Using System;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
public class Udpmulticastlistener {
Ipaddress.parse ("224.168.100.2");
Private Const int groupport = 11000;
private static void Startlistener () {
bool done = false;
UdpClient listener = new UdpClient ();
IPEndPoint Groupep = new IPEndPoint (groupaddress,groupport);
try {
Listener. Joinmulticastgroup (groupaddress);
Listener. Connect (GROUPEP);
while (!done) {
Console.WriteLine ("Waiting for broadcast");
byte[] bytes = listener. Receive (ref GROUPEP);
Console.WriteLine ("Received broadcast from {0}: \ n {1}\n",
Groupep.tostring (),
Encoding.ASCII.GetString (bytes,0,bytes. Length));
}
Listener. Close ();
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}
public static int Main (string[] args) {
Startlistener ();
return 0;
}
}

The following example uses theUdpClientSends the UDP datagram to the multicast address group 224.268.100.2 on port 11000. It sends the message string specified on the command line.
[C #]
Using System;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
public class Udpmulticastsender {
Ipaddress.parse ("224.168.100.2");
private static int groupport = 11000;
private static void Send (String message) {
UdpClient sender = new UdpClient ();
IPEndPoint Groupep = new IPEndPoint (groupaddress,groupport);
try {
Console.WriteLine ("Sending datagram: {0}", message);
byte[] bytes = Encoding.ASCII.GetBytes (message);
Sender. Send (bytes, bytes. Length, GROUPEP);
Sender. Close ();
catch (Exception e) {
Console.WriteLine (E.tostring ());
}
}
public static int Main (string[] args) {
Send (Args[0]);
return 0;
}
}

Sockets


The System.Net.Sockets namespace contains a managed implementation of the Windows socket interface. All other network access classes in the System.Net namespace are based on the socket implementation.
The. NET framework Socket class is the managed code version of the socket service provided by the Winsock32 API. In most cases,SocketThe class method simply marshals the data to their native Win32 copy and handles any necessary security checks.
SocketClasses support two basic modes: synchronous and asynchronous. In synchronous mode, calls to functions that perform network operations, such as Send and Receive, wait until the operation completes before returning control to the calling program. In asynchronous mode, these calls are returned immediately.

Creating sockets


Before you can use sockets to communicate with a remote device, you must initialize the socket using protocol and network address information. The constructor for the Socket class has parameters for the address family, socket type, and protocol type that the specified socket uses to establish the connection. The following example creates aSocket, which can be used to communicate on a TCP/ip-based network, such as the Internet.
[C #]
SocketType.Stream, PROTOCOLTYPE.TCP);

To use UDP instead of TCP, change the protocol type, as shown in the following example.
[C #]
Sockettype.dgram, PROTOCOLTYPE.UDP);

AddressFamily enumeration SpecifiesSocketClass is used to resolve the standard address family of a network address (for example,AddressFamily.InterNetworkThe member specifies the IP version 4 address family).
SocketType enumeration Specifies the type of socket (for example,SocketType.StreamA member indicates a standard socket that is used to control the sending and receiving of data through a stream.
The ProtocolType enumeration specifies that theSocketThe network protocol used when communicating on (for example,protocoltype.tcpIndicates that the socket uses TCP;protocoltype.udpIndicates that the socket uses UDP.
CreateSocket, it can either initialize a connection to a remote endpoint or receive a connection from a remote device.

Using Client sockets


Before you can initialize the dialog through the Socket, you must create a data pipeline between the application and the remote device. Although there are other network address families and protocols, this example shows how to create a TCP/IP connection to a remote service.
TCP/IP uses a network address and a service port number to uniquely identify the device. The network address identifies a specific device on the network, and the port number identifies the specific service on the device to which you want to connect. The combination of network address and service port is called an endpoint, which is represented by the EndPoint class in the. NET framework. defined for each supported address familyEndPoint, and for the IP address family, the class is IPEndPoint.
The Dns class provides domain name services to applications that use TCP/IP Internet services. The Resolve method queries the DNS server to map user-friendly domain names (such as "host.contoso.com") to digital forms of Internet addresses (such as 192.168.1.1).ResolveReturns a Iphostenty instance that contains a list of addresses and aliases for the requested name. In most cases, you can use the first address returned in the AddressList array. The following code gets a IPAddress instance that contains the IP address of the server host.contoso.com.
[C #]
Iphostentry iphostinfo = dns.resolve ("host.contoso.com");
IPAddress ipaddress = iphostinfo.addresslist[0];

The Internet Allocation number Authority (Internet assigned Numbers Authority, IANA) defines the port number of the public service (for more information, visit the http://www.iana.org/assignments/ Port-numbers). Other services can have a registered port number in the range 1,024 through 65,535. The following code combines the IP address of the host.contoso.com with the port number to create a remote endpoint for the connection.
[C #]
IPEndPoint ipe = new IPEndPoint (ipaddress,11000);

After the address of the remote device is determined and the port used for the connection is selected, the application can attempt to establish a connection to the remote device. The following example uses the existingIPEndPointinstance to a remote device and catches any exceptions thrown.
[C #]
try {
S.connect (IPE);
catch (ArgumentNullException ae) {
Console.WriteLine ("ArgumentNullException: {0}", Ae. ToString ());
catch (SocketException se) {
Console.WriteLine ("SocketException: {0}", se.) ToString ());
catch (Exception e) {
Console.WriteLine ("Unexpected exception: {0}", e.tostring ());
}

Using synchronous client sockets


Synchronous client sockets suspend the application while waiting for the network operation to complete. Synchronous sockets do not apply to applications that use the network heavily in operations, but they can enable simple access to network services for other applications.
To send data, pass a byte array to one of the data-sending methods (send and SendTo) of the Socket class. The following example uses the Encoding.ascii property to encode a string into a byte array buffer and then use theSendmethod to transfer the buffer to a network device.Sendmethod returns the number of bytes sent to a network device.
[C #]
byte[] msg = System.Text.Encoding.ASCII.GetBytes ("This is a Test");
int bytessent = S.send (msg);

Sendmethod to remove the bytes from the buffer and queue them for transmission to the network device using the network interface. The network interface may not send data immediately, but it will eventually be sent as long as the connection is normally closed with the Shutdown method.
To receive data from a network device, pass the buffer to theSocketOne of the data-receiving methods (receive and ReceiveFrom) for the class. The synchronization socket suspends the application until the byte is received from the network or the socket is closed. The following example receives data from the network and then displays it on the console. This example assumes that the data from the network is ASCII-encoded text.Receivemethod returns the number of bytes received from the network.
[C #]
byte[] bytes = new byte[1024];
int bytesrec = s.receive (bytes);
Console.WriteLine ("echoed Text = {0}",
System.Text.Encoding.ASCII.GetString (bytes, 0, Bytesrec));

You need to release the socket when you no longer need it, by calling the Shutdown method, and then calling the CloseMethod. The following example releasesSocket。 The SocketShutdown enumeration defines constants to indicate whether to turn off sockets for sending, sockets for receiving, or sockets for both.
[C #]
S.shutdown (Socketshutdown.both);
S.clos


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.