C#. NET Network program Development-TCP article

Source: Internet
Author: User
Tags bool ftp getstream implement connect socket tostring port number
Program | Network before a "Visual C #." NET Network program development-socket: The classes that support HTTP, TCP, and UDP form the middle tier-application protocol layer of the TCP/IP three-layer model (Request response Layer, application protocol layer, Transport layer), where the analogy at the bottom of the socket class provides a higher level of abstraction, They encapsulate the creation of TCP and UDP sockets and do not need to handle the details of the connection, which makes it possible to try more with TcpClient, UdpClient, and TcpListener when writing socket-level protocols, rather than writing directly to the socket. This hierarchical relationship between them is indicated as follows:
???
?? Visible, the TcpClient class is built based on the Socket class, which is the basis for its ability to provide TCP services at a higher level of abstraction. Because of this, communication protocols on many application tiers, such as FTP (file transfers Protocol) files Transfer Protocol, HTTP (hypertext transfers Protocol) Hypertext transfer protocols are created directly on top of tcpclient classes.
???
?? The TcpClient class uses TCP to request data from Internet resources. 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.
???
?? As you can see from the name, the TcpClient class is designed for clients and provides client connectivity for TCP network services. TcpClient provides a simple way to connect, send, and receive data over a network.
???
?? To establish a TCP connection, you must know the address of the network device that hosts the required services (IPAddress) 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 (you can access http://www.iana.org/assignments/ Port-numbers obtained more detailed information in this regard). Services that are not in the IANA list can use the port number in the range 1,024 through 65,535. To create this connection, you can select one of the three constructors of the TcpClient class:
???
?? 1. Public TcpClient () when using this constructor with no parameters, the native default IP address will be used and the default communication port number 0 will be used. In this case, if there is more than one IP address on this computer, you will not be able to choose to use it. The following statement examples how to use the default constructor to create a new tcpclient:
???
?? TcpClient TCPCLIENTC = new TcpClient ();
???
???
?? 2. Public TcpClient (IPEndPoint) uses native IPEndPoint to create tcpclient instance objects. As described in the previous article, ipendpoint the network endpoint as an IP address and port number, where it is used to specify the local network interface (IP address) and port number to use when establishing a remote host connection, which provides the option to use native IPAddress and port. The following statement examples how to use a local endpoint to create an instance of the TcpClient class:
???
?? Iphostentry ipinfo=dns.gethostbyname ("www.tuha.net");/host Information
??? Ipaddresslist[] IPLIST=IPINFO.ADDRESSLIST;//IP Address array
??? IPAddress ip=iplist[0];//multiple IP addresses typically use the first
??? IPEndPoint ipep=new IPEndPoint (ip,4088)//Get network Endpoint
??? try{
??? TcpClient Tcpclienta = new TcpClient (iplocalendpoint);
???}
?? catch (Exception e) {
??? Console.WriteLine (E.tostring ());
???}
???
???
?? Here, you may be confused, the client to create a connection with the server, the specified IP address and communication port number should be remote servers! As a matter of fact, with both of these constructors, all you can do is bind tcpclient instance objects to IP addresses and port ports, and to complete the connection you also need to explicitly specify the connection to the remote host, which is implemented by the Connect method of the TcpClient class. The Connet method connects the client to a remote host using the specified host name and port number:
???
?? 1), public void Connect (IPEndPoint); Connects a client to a remote TCP host using the specified remote network endpoint.
???
?? public void Connect (ipaddress, int); Connects the client to the TCP host using the specified IP address and port number.
???
?? public void Connect (string, int); Connects the client to the specified port on the specified host.
???
?? It should be noted that all the overloaded forms of the Connect method are IPEndPoint the network end
???
?? Nodes, IPAddress, and DNS host names represented as string and port ports indicated by int refer to the remote server.
???
?? The following example statement establishes a connection to a remote host using the host default IP and port port number 0:
???
?? TcpClient tcpclient = new TcpClient ();//Create TcpClient object instance
??? try{
??? Tcpclient.connect ("www.contoso.com", 11002);//Establish a connection
???}
??? catch (Exception e) {
??? Console.WriteLine (E.tostring ());
???}
???
???
?? 3. Public TcpClient (string, int); Initializes a new instance of the TcpClient class and connects to the specified port on the specified host. Unlike the first two constructors, this constructor automatically establishes the connection, and you no longer need to call the Connect method extra, where string parameters represent the DNS name of the remote host, such as: Www.tuha.net.
???
?? The following example statement calls this method to implement a host that is connected to the specified host name and port number:
???
?? try{
??? TcpClient TCPCLIENTB = new TcpClient ("Www.tuha.net", 4088);
???}
??? catch (Exception e) {
??? Console.WriteLine (E.tostring ());
???}
?? We say that the TcpClient class is created on top of the socket, providing a higher level of abstraction in the TCP service, which is reflected in the sending and receiving of network data, and is tcpclient use standard stream stream processing technology to make it read and write data more convenient and intuitive, at the same time. NET Framework is responsible for providing richer structures to handle streams throughout. NET Framework with more extensive compatibility, a common approach built on more general flow operations allows us to no longer need to be confused with the actual content of the file (HTML, XML, or anything else), and the application will use a consistent approach (Stream.Write, Stream.read) Send and receive data. In addition, streams provide instant access to data when data is downloaded from the Internet and can begin processing as soon as some data arrives without waiting for the application to download the entire dataset ... NET implements these processing techniques through the NetworkStream class.
???
?? The NetworkStream class is contained in the. Net Framework, this class specifically provides the underlying data flow for network access. \ System.Net.Sockets NetworkStream implements the standard. Net framework flow mechanism for sending and receiving data over a network socket. NetworkStream supports synchronous and asynchronous access to network data streams. NetworkStream inherits from Stream, which provides a rich set of methods and properties for easy network communication.
???
?? Like all streams that inherit from the abstract base class stream, NetworkStream network streams can also be treated as a data channel, between the data source (client client) and the receiving End (service server), and the subsequent data reads and writes are directed at this channel.
???
??. NET Framework, the NetworkStream stream supports both operations:
???
?? 1, write stream. Writes are data transfer from the data structure to the stream.
???
?? 2, read stream. Reading is a data transfer from a stream to a data structure, such as a byte array.
???
?? Unlike a regular stream stream, the network stream does not have a unified concept of the current position and therefore does not support lookups and random access to the data stream. The corresponding property CanSeek always returns False, and the Seek and Position methods also raise the NotSupportedException.
???
?? Based on the application protocol on the socket, you can obtain the NetworkStream network data flow in the following two ways:
???
?? 1. Use the NetworkStream constructor: Public NetworkStream (Socket, FileAccess, BOOL); (with overloaded methods), it is created with the specified access rights and the specified socket ownership for the specified socket A new instance of the NetworkStream class, you need to create a socket object instance before use, and through the Socket.connect method to establish a connection with the remote server, then you can use this method to obtain network transport flow. Examples are as follows:
???
?? Socket s=new socket (ADDRESSFAMILY.INTERNETWORK,SOCKETTYPE.STREAM,PROTOCOLTYPE.TCP);//Create client socket object instance
??? try{
??? S.connect ("Www.tuha.net", 4088);//Establish a connection to the remote host
???}
??? catch (Exception e) {
??? MessageBox.Show ("Connection error:" +e.message);
???}
??? try{
??? NetworkStream stream=new NetworkStream (s,fileaccess.readwrite,false);//Get Network transport Stream
???}
???
???
?? 2. Through Tcpclient.getstream method: Public NetworkStream Etstream (), which returns the underlying network stream NetworkStream for sending and receiving data. GetStream creates an instance of the NetworkStream class by using the base Socket as its constructor parameter. Before using, you need to create a TcpClient object instance and establish a connection to the remote host, as shown in the following example:
???
?? TcpClient tcpclient = new TcpClient ();//Create TcpClient object instance
??? try{
??? Tcpclient.connect ("Www.tuha.net", 4088);//trying to connect to a remote host
???}
??? catch (Exception e) {
??? MessageBox.Show ("Connection error:" +e.message);
???}
??? try{
??? NetworkStream Stream=tcpclient.getstream ()//Get network transport Stream
???}
??? catch (Exception e)
??? {
??? MessageBox.Show ("TcpClient error:" +e.message);
???}
???
???
?? By using the above method to get the NetworkStream network stream, you can use the standard stream read and write methods write and read to send and receive data.
???
?? The above is. NET uses the TcpClient class to implement the client programming technical data, in order to provide these services to the client, we also need to compile the corresponding server program, the previous article "Visual C #". NET Network program development-socket once mentioned, socket as the basis of other network protocols, both for client development, but also for service-side development, at the transmission level, and in the application protocol level, Client we use the TcpClient built on the socket to replace the socket; Accordingly, the TcpListener built on top of the socket provides a higher level of TCP service, making it easier for us to write service-side applications. It is for this reason that application layer protocols such as FTP and HTTP are built on the basis of the TcpListener class.
???
??. NET to monitor incoming requests on TCP ports, create TcpListener object instances by binding the machine IP address and the corresponding port (which should be consistent with the client's request), and start listening by the Start method TcpListener When TcpListener detects a connection to a client, accepts incoming connection requests and creates tcpclient to process the request, depending on the different requests of the clients, either through the AcceptTcpClient method, or through the AcceptSocket Method accepts incoming connection requests and creates a Socket to process the request. Finally, you need to turn off the Socket used to listen for incoming connections by using Stop, and you must also close any instances returned from AcceptSocket or accepttcpclient. This process is explained in detail as follows:
???
?? First, create an instance of the TcpListener object, which is implemented through the construction of the TcpListener class:
???
?? Public TcpListener (port);//Specify native port
?? Public TcpListener (IPEndPoint)//specifies a native endpoint
?? Public TcpListener (Ipaddress,port)//Specify native IP address and port
???
???
?? The parameters in the above method are mentioned several times earlier, and there is no more detail here, the only thing to be reminded is that these parameters are for the server-side host. The following example shows an instance of creating a TcpListener class:
???
?? Iphostentry ipinfo=dns.resolve ("127.0.0.1");/host Information
??? Ipaddresslist[] IPLIST=IPINFO.IPADDRESSLIST;//IP Array
??? IPAddress IP=IPLIST[0];//IP
??? try{
??? TcpListener TcpListener = new TcpListener (ipaddress, 4088);//Create a TcpListener object instance to listen for client connections
???}
??? catch (Exception e) {
??? MessageBox.Show ("TcpListener error:" +e.message);
???}
???
???
?? Then you need to invoke the Start method to start listening:
???
?? public void Start ();
???
???
?? Second, when the listener hears a client connection, it needs to accept a pending connection request, which completes the connection by calling one of the following two methods:
???
?? Public Socket acceptsocket ();
?? Public TcpClient accepttcpclient ();
???
???
?? The previous method returns the socket object representing the client, which can then communicate with the remote computer through the Send and Receive methods of the socket class, and the latter returns the TcpClient object representing the client, followed by the The Tcpclient.getstream method obtains TcpClient's underlying network stream NetworkStream and communicates with the remote computer using the stream read-write Read/write method.
???
?? Finally, remember to close the listener: public void Stop ();
???
?? Also close other connection instances: public void close ();
???
?? The following example is a complete representation of the above procedure:
???
?? bool done = false;
??? TcpListener listener = new TcpListener (13);//Create TcpListener object instance (port 13th provides time service)
??? Listener. Start ()//Initiate listening
??? while (!done) {//Enter an infinite loop to listen for user connections
??? TcpClient client = listener. AcceptTcpClient ()//To create a client connection after hearing the connection TcpClient
??? NetworkStream ns = client. GetStream ()//Get network transport Stream
??? byte[] Bytetime = Encoding.ASCII.GetBytes (DateTime.Now.ToString ())//Pre-sent content (this is server-side time) converted to byte array for write inflow
??? try {
??? Ns. Write (bytetime, 0, bytetime.length);/writes Inflow
??? Ns. Close ();//Off stream
??? Client. Close ()//Shut down client connections
???}
?? catch (Exception e) {
??? MessageBox.Show ("Stream error:" +e.message)
???}
???????? Comprehensive use of the above knowledge, the following examples to achieve a simple network communication-dual-computer interconnection, for the client and server-side separately compiled the application. The client creates a connection to the server, sends a connection request connection signal to the remote host, sends the conversation content, and the remote host receives a connection from the client, sends back a signal to the client confirming the connection, and receives and displays the conversation content of the client. On this basis, play your creativity, you can fully develop a program language (C #)-level chat room!
???
?? Client Main Source code:
???
??? public void Sendmeg ()/Send information
??? {
?? Try
?? {
???
???
?? int Port=int32.parse (textBox3.Text.ToString ());//Remote host port
??? Try
??? {
??? Tcpclient=new TcpClient (Textbox1.text,port);//Create TcpClient object instance}
??? catch (Exception le)
??? {
??? MessageBox.Show ("TcpClient Error:" +le.) message);
???}
?? String strdateline=datetime.now.toshortdatestring () + "" +datetime.now.tolongtimestring ()//Get client time when sent
??? Netstream=tcpclient.getstream ()//Get network stream
??? Sw=new StreamWriter (NetStream);//create TextWriter, write characters to stream
??? String words=textbox4.text;//to be sent
??? String content=strdateline+words;//content to be sent
??? Sw. Write (content);//Writes Inflow
??? Sw. Close ();//Shut down stream writer
??? Netstream.close ()//Close network stream
??? Tcpclient.close ()//Close Client Connection
??}
?? catch (Exception ex)
??? {
??? MessageBox.Show ("Sending message failed!") +ex. message);
???}
??? Textbox4.text= "";/Empty
???}
???
???
?? Server-side main source code:
???
??? public void Startlisten ()//listening to a user request for a specific port
??? {
?? Receivemeg ();
?? Islinked=false; Connection Flags
??? Try
??? {
??? int Port=int32.parse (textBox1.Text.ToString ());//local listening port
??? Serverlistener=new TcpListener (port);//Create TcpListener object instance
??? Serverlistener.start (); Start listening
???}
??? catch (Exception ex)
??? {
??? MessageBox.Show ("Can ' t Start Server" +ex.) message);
??? Return
???}
??? Islinked=true;
??? while (true)/Enter an infinite loop waiting for the client to connect
??? {
??? Try
??? {
??? Tcpclient=serverlistener.accepttcpclient ();//Create Client Connection object
??? Netstream=tcpclient.getstream ()//Get network stream
??? Sr=new StreamReader (NetStream);//Stream Reader
???}
??? catch (Exception re)
??? {
??? MessageBox.Show (re. message);
???}
??? String Buffer= "";
?? String Received= "";
??? RECEIVED+=SR. ReadLine ()//a line in the read stream
??? while (Received. length!=0)
??? {
??? buffer+=received;
??? buffer+= "\ r \ n";
??? Received= "";
??? RECEIVED=SR. ReadLine ();
???}
?? LISTBOX1.ITEMS.ADD (buffer)//display
?? Shut down
?? Sr. Close ();
?? Netstream.close ();
?? Tcpclient.close ();
??}
??}?



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.