Use .NET to access Internet (3)

zhaozj2021-02-17  54

Use TCP service

The TCPCLIENT class uses TCP request data from the Internet resource. TCPClient's method and attribute extracts the creation details of a Socket instance, which is used to request and receive data through TCP. Since the connection to the remote device is expressed as a stream, you can read and write data using the .NET framework flow processing technology.

The TCP protocol establishes a connection with the remote endpoint and then uses this connection to send and receive the packet. TCP is responsible for ensuring that the packet is sent to the endpoint and combined in the correct order when the packet arrives.

To establish a TCP connection, you must know the address of the network device that carries the desired service and the TCP port used to communicate. Internet Assigned Numbers Authority (IANA) Defines the port number of public services (please visit http://www.iana.org/assignments/port-numbers). The services in the IANA list can use the port numbers in this range of 1,024 to 65, 535.

The following code explains how to set TCPCLIT to connect to the 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 the incoming request on the TCP port, then create a socket or tcpclient instance to manage the connection with the client. The Start method enables listening, and the STOP method disables the listening on the port. AcceptTCPClient methods Accept the incoming connection request and create TCPClient to process the request, accept the incoming connection request and create a Socket to process the request.

The following code shows how to create a network time server using TCPListener to monitor TCP ports 13. When the incoming connection request is received, 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;

}

}

Use UDP service

UDPCLIENT class uses UDP and network service communication. The properties and methods of the UDPCLIENT class extracts the creation details of a Socket instance, which is used to request and receive data through the UDP.

The advantage of UDP is simple and easy to use and can broadcast messages to multiple addresses simultaneously. However, since the UDP protocol is a connectionless protocol, the UDP data text reported to the remote endpoint is not necessarily to be reached, and it is not necessarily to be reached in the same order of transmission. Using UDP applications must prepare data textbooks that handle lost and order.

To send a data credit using a UDP, you must know the network address of the network device that carries the required service and the UDP port number for communication. Internet Assigned Numbers Authority (IANA) Defines the port number of public services (please visit http://www.iana.org/assignments/port-numbers). The services in the IANA list can use the port numbers in this range of 1,024 to 65, 535.

Special network addresses are used to support UDP broadcast messages on an IP-based network. The content discussed below is an example of an IP version 4 address family used on the Internet.

IP version 4 address uses 32-bit specified network addresses. These bits are divided into four eight bytes for Class Class Class Class 2555.255.255.0. When a decimal number is represented, these four eight bytes constitute familiar four-part representations, such as 192.168.100.2. The first two eight-bit bytes (192.168 in this example) constitute the network number; the third eight-bit byte (100) defines the subnet; the last eight-bit byte (2) is the host identifier.

All bits of the IP address are set to 1 (ie 255.255.255.255) may constitute a limited broadcast address. Sending UDP Data Libaration to this address to pass messages to any host on the broadcast network. Since the router does not forward the message sent to this address, only the hosts on the connected network can see these broadcasts.

By setting all the bits of the partial address to 1, the broadcast can be oriented to a particular network portion. For example, to send a broadcast to all hosts on the network identified by the IP address of 192.168, all hosts are set to 1, such as 192.168.255.255. To limit the broadcast to a single subnet, only the host part is set to 1, such as 192.168.100.255.

The UDPCLIENT class can broadcast address to any network broadcast address, but it cannot listen to the broadcast sent to the network. You must use the Socket class to listen to the network broadcast.

When all recipients are in a single network, or when many clients need to receive broadcasts, the broadcast address will work. When the recipient is a small portion of the network, the message should be sent to multiple broadcast groups where only the client is added to the message can be received. The IP address from 224.0.0.0.0.2 to 244.255.255.255 is reserved as the host group address. IP 224.0.0.0 is preserved, while 224.0.0.1 assigns a fixed group of all IP hosts. The following example broadcasts the UDP data text report broadcast of multiple broadcast addresses 224.168.100.2 on the UDPClient listener port 11000. 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 {

Private static readonly ipaddress groupaddress =

Ipaddress.Parse ("224.168.100.2");

Private const Int groupport = 11000;

Private static void startlistener () {

Bool Done = false;

UDPCLIENT LISTENER = New udpclient ();

IpendPoint GroupP = New IpendPoint (GroupAddress, GroupPort);

Try {

Listener.joinmulticastGroup (GroupAddress);

Listener.Connect (GroupP);

While (! done) {

Console.writeline ("Waiting for Broadcast");

Byte [] bytes = listener.Receive (Ref group);

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 UDPClient to send UDP data text reports to multiple broadcast addresses 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 {

Private static ipaddress groupAddress =

Ipaddress.Parse ("224.168.100.2");

Private static int groupport = 11000;

Private static void send (string message) {

UDPCLIENT Sender = new udpclient ();

IpendPoint GroupP = New IpendPoint (GroupAddress, GroupPort);

Try {

Console.writeline ("Sending DataGram: {0}", Message); Byte [] Bytes = Encoding.AScii.GetBytes (Message);

Sender.send (Bytes, Bytes.Length, GroupP);

Sender.close ();

} catch (exception e) {

Console.writeLine (E.TOString ());

}

}

Public static int main (string [] args) {

Send (Args [0]);

Return 0;

}

}

Socket

System.net.sockets namespace contains managed implementations for Windows socket interfaces. All other network access classes in the System.Net Namespace are built on the socket implementation.

The .NET Framework Socket class is a managed code version of the socket service provided by Winsock32 API. In most cases, the Socket class method is just to send data to their local WIN32 copies and handle any necessary security checks.

The Socket class supports two basic modes: synchronous and asynchronous. In synchronization mode, the call to the function of the network operation (such as Send and Receive) will continue to return the control to the call after the operation is completed. In asynchronous mode, these calls return immediately.

Create a socket

Protocol and network address information initialization socket must be initialized using a socket with the remote device communication. The constructor of the Socket class has parameters for specifying sockets, socket types, and protocol types that specify sockets. The following example creates an Socket that can be used to communicate on a TCP / IP network (such as the Internet).

[C #]

Socket S = New Socket (AddressFamily.InterneTwork,

Sockettype.stream, protocoltype.tcp;

To use UDP instead of TCP, change the protocol type, as shown in the example below.

[C #]

Socket S = New Socket (AddressFamily.InterneTwork,

Sockettype.dgram, protocoltype.udp);

AddressFamily enumerates the specified Socket class to parse the standard address family of the network address (for example, the AddressFamily.InterneTWork member specifies the IP version 4 address family).

SocketType enumerates the type of specified socket (for example, the sockettype.stream member indicates a standard socket for sending and receiving data by stream).

The ProtocolType enumerates a network protocol that specifies when communicating on the socket (for example, protocoltype.tcp indicating socket uses TCP; protocoltype.udp indicates that the socket uses UDP).

After creating a socket, it can initialize the connection with the remote endpoint, or you can receive a connection from the remote device.

Use client socket

A data pipe must be created between the application and the remote device before the Socket initialization dialog. Although there are other network address families and protocols, this example shows how to create a TCP / IP connection with the remote service.

TCP / IP uses a network address and a service port number to uniquely identify the device. Network Address Identify Specific Device on the Network; port number identifies specific services to which the device to be connected. The combination of network addresses and service ports is called endpoints, which are represented by the EndPoint class in the .NET framework. Define the sub-generation of EndPoint for each supported address family; for the IP address family, this 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 the user-friendly domain name (such as "host.contoso.com" to the digital form of Internet address (eg 192.168.1.1). Resolve returns an iPhostenty instance that contains the list of addresses and alias of the requested name. In most cases, you can use the first address returned in the AddressList array. The following code acquires an 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];

Internet Assigned Numbers Authority (IANA) Defines the port number of public services (for more information, please visit http://www.iana.org/assignments/port-numbers). Other services can have registration port numbers within the range of 1, 024 to 65, 535. The following code combines host.contoso.com with port number to create remote endpoints for connectivity.

[C #]

IpendPoint Ipe = New IpendPoint (ipaddress, 11000);

The address of the remote device is determined and the port used to connect, the application can attempt to establish a connection to the remote device. The following example uses an existing IpendPoint instance to connect to a remote device, and capture any exceptions caused.

[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 ());

}

Use synchronous client socket

Synchronous client sleeve launches the application when waiting for the network operation to complete. Synchronous sockets do not apply to applications that use the network in operation, but they can enable simple access to network services to other applications.

To send data, pass the byte array to one of the data transmission methods (Send and Sendto) of the Socket class. The following example uses the Encoding.ascii property to encode the string into the byte array buffer, then transfer the buffer to the network device using the Send method. The Send method returns the number of bytes sent to the network device.

[C #]

Byte [] msg = system.text.Encoding.ascii.getbytes ("this is a test");

INT BYTESSENT = S.Send (MSG); the Send method removes bytes from the buffer and queues these bytes with the network interface to send to the network device. The network interface may not send data immediately, but it will eventually be sent, as long as the connection is to use the shutdown method to close.

To receive data from the network device, pass the buffer to one of the data receiving methods of the Socket class (Receive and ReceiveFrom). The synchronization socket will hang the application until it is closed from the network reception byte or socket. The following example receives data from the network and is displayed on the console. This example assumes that data from the network is text encoded with ASCII. Receive method 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);

Needless to release it when you need a socket, the specific method is to call the shutdown method and then call the Close method. The following example releases socket. The SocketShutdown enumeration definition is often the indication to turn off the socket used to send, and the socket for receiving is still used for both sockets.

[C #]

S.SHUTDOWN (SocketShutdown.both);

s.close ();

转载请注明原文地址:https://www.9cbs.com/read-28553.html

New Post(0)