Use C # To implement TCP-based Network Communication

Source: Internet
Author: User
Tags getstream
TCP is a basic network protocol. Basically, all network services are based on TCP, such as HTTP and FTP, therefore, to understand network programming, you must understand TCP-based programming. However, TCP is a complex system. It is not a day or two to realize it. Fortunately. in the. NET Framework environment, we do not have to investigate the implementation of the TCP protocol at the underlying layer. In the same way, we can easily compile network communication based on the TCP protocol. Program .

For TCP-based network communication, you must first establish a connection with a remote host. The connection address usually consists of two parts: host name and port. For example, in www.yesky.com: 80, www.yesky.com is the host name, port 80 refers to port 80 of the host. Of course, the host name can also be replaced by an IP address. After the connection is established, you can use this connection to send and receive data packets. The role of the TCP protocol is to ensure that these data packets can reach the end point and be assembled in the correct order.

In the. NET Framework class library, two classes are provided for TCP network communication, namely tcpclient and tcplistener. The English meaning is obvious. The tcpclient class is a TCP-based client class, while the tcplistener is a server client that listens for connection requests from the listen client. The tcpclient class communicates with the server through the TCP protocol and obtains information. It encapsulates an instance of the socket class, which is used to request and obtain data from the server through the TCP protocol. Because the interaction with remote hosts occurs in the form of data streams, the transmitted data can be read and written using the. NET Framework streaming processing technology. In the following example, you can see how to use the networkstream class to operate data streams.

In the following example, we will create a time server, including the server and client programs. The server listens to client connection requests and sends the current system time to the client after the connection is established.

Run the server program first. The following shows the running status of the server program:

Then run the client program. The client first sends the connection request to the server, and then sends the current time to the client after the server responds.

After sending the message, the server continues to wait for the next connection:

In this example, we can understand the basic usage of the tcpclient class. To use this class, you must use the system. net. Socket namespace. The three namespaces used in this example are as follows:

Using system;
Using system. net. Sockets;
Using system. Text; // use the class in the namespace when obtaining a string from the byte array

First, let's discuss the client program. At first, we must initialize a tcpclient class instance:

Tcpclient client = new tcpclient (hostname, portnum );

Use the getstream () method of the tcpclient class to obtain the data stream and use it to initialize an instance of the networkstream class:

Networkstream NS = client. getstream ();

Note: When you use the host name and port number to initialize the tcpclient class instance, the program can be executed only after the connection is established with the server. If the connection fails because the network is disconnected, the server does not exist, and the server port is not open, the program throws an exception and interrupts execution.

After a data stream is created, we can use the read () method of the networkstream class to read data from the stream and use the write () method to write data to the stream. When reading data, we should first create a buffer. Specifically, we should create a byte array to store the data read from the stream. The prototype of the read () method is described as follows:

Public override int read (in byte [] buffer, int offset, int size)

Buffer is a buffer array, and offset is the starting position of data (byte stream) in the buffer array. size is the number of bytes read, and the return value is the number of bytes read. In this example, we simply use this method to read the server feedback:

Byte [] bytes = new byte [1024]; // create a buffer
Int bytesread = NS. Read (bytes, 0, bytes. Length); // read byte streams

Then displayed on the screen:

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

Finally, do not forget to close the connection:

Client. Close ();

The following is a complete program list in this example:

Using system;
Using system. net. Sockets;
Using system. text;

Namespace tcpclientexample
{
Public class tcptimeclient
{
Private const int portnum = 13; // server port, which can be modified at will
Private const string hostname = "127.0.0.1"; // server address. 127.0.0.1 indicates the local host.

[Stathread]
Static void main (string [] ARGs)
{
Try
{
Console. Write ("try to connect to" + hostname + ":" + portnum. tostring () + "\ r \ n ");
Tcpclient client = new tcpclient (hostname, portnum );
Networkstream NS = client. getstream ();
Byte [] bytes = new byte [1, 1024];
Int bytesread = NS. Read (bytes, 0, bytes. Length );

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

Client. Close ();
Console. Readline (); // because it is a console program, you can add this sentence to see the result clearly.

}
Catch (exception E)
{
Console. writeline (E. tostring ());
}
}
}
}

The above example clearly demonstrates the key points of writing the client program. Next we will discuss how to create a server program. In this example, the tcplistener class is used to listen on Port 13. Once a client is connected, the time information of the current server will be sent to the client immediately.

The key to tcplistener is the accepttcpclient () method. This method checks whether there are unprocessed connection requests on the port. If there are unprocessed connection requests, This method enables the server to establish a connection with the client, in addition, a tcpclient object is returned, and the getstream method of this object is used to establish a data stream for communication with the client. In fact, the tcplistener class also provides a more flexible method for acceptsocket (). Of course, the flexible cost is complicated. For simple programs, accepttcpclient () is enough. In addition, the tcplistener class provides the START () method to start listening and the STOP () method to stop listening.

First, we use the port to initialize a tcplistener instance and start listening on Port 13:

Private const int portnum = 13;
Tcplistener listener = new tcplistener (portnum );
Listener. Start (); // start listening

If there are unprocessed connection requests, use the accepttcpclient method for processing and obtain the data stream:

Tcpclient client = listener. accepttcpclient ();
Networkstream NS = client. getstream ();

Then, get the local time and save it in the byte array. Use the networkstream. Write () method to write data streams. Then the client can obtain this information from the data streams through the read () method:

Byte [] bytetime = encoding. ASCII. getbytes (datetime. Now. tostring ());
NS. Write (bytetime, 0, bytetime. Length );
NS. Close (); // do not forget to close data streams and connections.
Client. Close ();

The complete program list on the server side is as follows:

Using system;
Using system. net. Sockets;
Using system. text;

Namespace timeserver
{
Class timeserver
{
Private const int portnum = 13;

[Stathread]
Static void 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 ();
}
}
}

Compile and run the above two programs separately. OK. We have used C # To implement network communication based on the TCP protocol. How can this problem be solved? Easy!

using the basic method described above, we can easily compile some useful programs, such as FTP, email sending and receiving, and point-to-point instant messaging, you can even compile a QQ program by yourself!

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.