Differences between socket and tcplistener, tcpclient, and udpclient

Source: Internet
Author: User
Tags getstream

Differences between socket and tcplistener, tcpclient, and udpclient

Abstract: applications can use the Transmission Control Protocol (TCP) and user data packet protocol (UDP) services through tcpclient, tcplistener, and udpclient ......

Applications can use the Transmission Control Protocol (TCP) and user data packet protocol (UDP) services through tcpclient, tcplistener, and udpclient. These protocol classes are based on the system. net. sockets. Socket class, responsible for data transmission details. (Tcpclient, tcplistener, and udpclient are used to simplify socket)

Tcpclient and tcplistener use the networkstream class to represent the network. Use the getstream method to return the network stream, and then call the Read and Write methods of the stream. Networkstream does not have a basic socket for the Protocol class, so disabling it does not affect the socket.

The udpclient class uses byte arrays to save UDP data packets. Use the send method to send data to the network, and use the receive method to receive incoming data packets.

1. tcpclient
The tcpclient class provides some simple methods for connecting, sending, and receiving stream data through the network in synchronous blocking mode. To enable tcpclient to connect and exchange data, the tcplistener or socket created using TCP protocoltype must listen for incoming connection requests. You can use either of the following two methods to connect to the listener:
(1) create a tcpclient and call one of the three available connect methods.
(2) create a tcpclient using the host name and port number of the remote host. This constructor will automatically try a connection.
To send and receive data to the successor, use the getstream method to obtain a networkstream. Call the write and read methods of networkstream to send and receive data between the remote host. Use the close method to release all resources associated with tcpclient.

The following example shows how to use tcpclient to connect to the server:

Using system;

Using system. Collections. Generic;

Using system. text;

Using system. net. Sockets;

Using system. net;

Namespace tcpclient

{

Class Program

{

Private Static int portnum= 11000;

Private Static string hostname = DNS. gethostname (). tostring ();

Public static void main (string [] ARGs)

{

Try

{

Console. writeline ("Host Name:" + DNS. gethostname ());

Console. writeline ("Host IP Address:" + DNS. gethostaddresses (DNS. gethostname () [0]);

Tcpclient client = new tcpclient (hostname, portnum );

Networkstream NS = client. getstream ();

Byte [] bytes = new byte [1, 1024];

Int bytesread = NS. Read (bytes, 0, bytes. Length );

// Decodes byte streams into strings

Console. writeline (encoding. ASCII. getstring (bytes, 0, bytesread ));

Client. Close ();

}

Catch (exception E)

{

Console. writeline (E. tostring ());

}

}

}

}

2. tcplistener
The tcplistener class provides some simple methods for listening to and receiving incoming connection requests in the blocking synchronous mode. You can use tcpclient or socket to connect to tcplistener. You can use ipendpoint, local IP address, and port number, or only the port number to create a tcplistener. You can specify the local IP address as any and the local port number as 0 (if you want the basic service provider to assign these values to you ). If you choose to do this, you can use the localendpoint attribute after connecting to the socket to identify the specified information.

The start method is used to start listening for incoming connection requests. Start will queue incoming connections until you call the stop method or it has completed maxconnections queuing. You can use acceptsocket or accepttcpclient to extract connections from the incoming connection request queue. These two methods will be blocked. To avoid blocking, You can first use the pending method to determine whether there are available connection requests in the queue.

Call the stop method to disable tcplistener.

The following example shows how to use tcplistener to listen to client requests:
Using system;

Using system. Collections. Generic;

Using system. text;

Using system. net. Sockets;

Using system. net;

Namespace tcpclient

{

Class Program

{

Private const int portnum= 11000;

Static void main (string [] ARGs)

{

Bool done = false;

// Tcplistener listener = new tcplistener (portnum); // according to vs2005 msdn, this method is no longer used

// The ipendpoint class identifies the network as an IP address and port number

Tcplistener listener = new tcplistener (New ipendpoint (IPaddress. Any, 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 ();

}

}

}

3. udpclient
The udpclient class provides some simple methods for sending and receiving unconnected UDP datagram packets in the blocking synchronous mode. Because UDP has no connection transmission protocol, you do not need to establish a remote host connection before sending and receiving data. However, you can use either of the following two methods to create a default Remote Host:

  • Use the remote host name and port number as parameters to create a udpclient instance.
  • Create an instance of the udpclient class and call the connect method.

You can use any method provided in udpclient to send data to a remote device. The receive method can be used to receive data from a remote host.
The udpclient method also allows you to send and receive multicast data packets. You can use the joinmulticastgroup method to reserve a udpclient to a multicast group. You can use the dropmulticastgroup method to cancel a subscription to udpclient from a multicast group.

The following example demonstrates UDP communication between different ports on the same host:

Listener:
Using system;

Using system. net. Sockets;

Using system. text;

Using system. net;

Using system. Threading;

Namespace udpclient2

{

Class Program

{

Static void main (string [] ARGs)

{

Try

{

Udpclient = new udpclient (12000 );

String returndata = "client_end ";

Do

{

Console. writeline ("the server receives data :............................. ");

Ipendpoint remoteipendpoint = new ipendpoint (IPaddress. Any, 0 );

// Here, the Client IP address and port number are obtained by referencing and passing values.

Byte [] receivebytes = udpclient. Receive (ref remoteipendpoint );

// Obtain client data here

Returndata = encoding. utf8.getstring (receivebytes );

// Encoding. ASCII. getstring (receivebytes); If ASCII is used, Chinese characters cannot be correctly processed.

Console. writeline ("this is the message server received ed:" + returndata. tostring ());

Thread. Sleep (3000 );

Console. writeline ("send data to the client :............................. ");

Udpclient. Connect (DNS. gethostname (). tostring (), 11000 );

// Sends a message to the host to which you have connected.

String sendstr = "I am from the server:" + datetime. Now. tostring ();

Byte [] sendbytes = encoding. utf8.getbytes (sendstr );

// Byte [] sendbytes = encoding. ASCII. getbytes (sendstr); If ASCII is used, Chinese characters cannot be correctly processed.

Udpclient. Send (sendbytes, sendbytes. Length );

Console. writeline ("this is the message server send:" + sendstr );

} While (returndata! = "Client_end ");

}

Catch (exception E)

{

Console. writeline (E. tostring ());

}

}

}

}

Client:
Using system;

Using system. net. Sockets;

Using system. text;

Using system. net;

Namespace udpclient

{

Class Program

{

Static void main (string [] ARGs)

{

Try

{

Udpclient = new udpclient (11000 );

// Send data to the server

Udpclient. Connect (DNS. gethostname (). tostring (), 12000 );

// Sends a message to the host to which you have connected.

String sendstr = "I am from the client:" + datetime. Now. tostring ();

Byte [] sendbytes = encoding. utf8.getbytes (sendstr );

// Byte [] sendbytes = encoding. ASCII. getbytes (sendstr); If ASCII is used, Chinese characters cannot be correctly processed.

Udpclient. Send (sendbytes, sendbytes. Length );

Console. writeline ("this is the message client send:" + sendstr );

// Wait for a response from the server. After receiving the response, the server displays the response and ends the conversation.

Ipendpoint remoteipendpoint = new ipendpoint (IPaddress. Any, 0 );

// Here, the Client IP address and port number are obtained by referencing and passing values.

Byte [] receivebytes = udpclient. Receive (ref remoteipendpoint );

// Obtain the server data

String returndata = encoding. utf8.getstring (receivebytes );

// Encoding. ASCII. getstring (receivebytes); If ASCII is used, Chinese characters cannot be correctly processed.

Console. writeline ("this is the message come from server:" + returndata. tostring ());

Udpclient. Close ();

}

Catch (exception E)

{

Console. writeline (E. tostring ());

}

}

}

}

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.