Using C # to implement network communication based on TCP protocol

Source: Internet
Author: User
Tags array ftp getstream implement connect socket tostring port number
Internet

TCP protocol is a basic network protocol, basically all network services are based on TCP protocol, such as Http,ftp and so on, so to understand the network programming must understand the TCP protocol based programming. However, the TCP protocol is a complex system, to fully understand its implementation is not a day two days of Kung Fu, fortunately, in the. NET Framework environment, we do not have to pursue the implementation of TCP protocol at the bottom, it is easy to write a TCP protocol based on the network communication program.

To conduct network traffic based on TCP protocol, you must first establish a connection to a remote host, which usually includes two parts--hostname and port, such as WWW.YESKY.COM:80, Www.yesky.com is the host name, 80 refers to the 80 port of the host, of course, the host name can also be replaced with IP address. Once the connection is established, the connection can be used to send and receive packets, and the TCP protocol is to ensure that the packets reach the end point and are assembled in the correct order.

In the class library of the. NET Framework, two classes are provided for TCP network traffic, namely TcpClient and TcpListener. It is obvious from its English meaning that the TcpClient class is a client class based on the TCP protocol, while TcpListener is a connection request from the server side listening to the client (Listen). The TcpClient class communicates with the server through a TCP protocol and obtains information, and its interior encapsulates an instance of the socket class that is used to request and retrieve data from the server using the TCP protocol. Because the interaction with the remote host occurs in the form of a data stream, the transmitted data can be read and written using the. NET Framework streaming technology. In our example below, you can see how to manipulate the data flow using the NetworkStream class.

In the following example, we will establish a time server, including server-side programs and client programs. The server listens to the client's connection request, establishes the connection, and sends the current system time to the client.

First run the server-side program, the screenshot below shows the status of the server-side program running:

Then run the client program, the client first send the connection request to the server side, server-side response to send the current time to the client, this is a screenshot of the client program:

When the send completes, the server side continues to wait for the next connection:

 This example allows us to understand the basic usage of the TcpClient class, in order to use this class, you must use the System.Net.Socket namespace, and this example uses the following three namespaces:

using System;
using System.Net.Sockets;
using system.text;//Use classes in this namespace when fetching strings from a byte array

First discuss the client program, beginning we must initialize an instance of the TcpClient class:

tcpclient client = new TcpClient (HostName, portnum);

Then use the GetStream () method of the TcpClient class to get the data stream and initialize an instance of a NetworkStream class with it:

networkstream ns = client. GetStream ();

Note that when initializing an instance of the TcpClient class with the hostname and port number, the instance is not actually established until the connection is established with the server, and the program can be executed down. If the server does not exist because the network is disconnected, the server port is not open, and so on, the program throws an exception and interrupts execution.

After the data flow is established, we can use the read () method of the NetworkStream class to read data from the stream and write the data to the stream using the Write () method. When reading data, you should first create a buffer, specifically, to create a byte array to hold 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 in which offset is the starting position of the data (byte stream) stored in the buffer array, the size is the number of bytes read, and the return value is the number of bytes read. In this case, simply use this method to read information about the server feedback:

byte[] bytes = new byte[1024];//Build buffer
int bytesread = ns. Read (bytes, 0, bytes. LENGTH);/Read Byte stream

Then display to 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 list of the procedures in this example:

using System;
using System.Net.Sockets;
using System.Text;

namespace Tcpclientexample
{
public class Tcptimeclient
{
private const INT portnum = 13;//Server port, can be modified arbitrarily
private Const string hostName = "127.0.0.1";//server address, 127.0.0.1 refers to native

[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[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, so in order to see the results clearly, you can add this sentence

}
catch (Exception e)
{
console.writeline (E.tostring ());
}
}
}
£}

The above example clearly demonstrates the key to writing a client program, so let's discuss how to create a server program. This example will use the TcpListener class to listen on Port 13th and, once there is a client connection, the current server's time information will be sent to the client immediately.
The key to tcplistener is the AcceptTcpClient () method, which detects whether the port has an unhandled connection request, and if there is an unhandled connection request, this method causes the server to connect to the client and returns a TcpClient object. The GetStream method of this object is used to establish a data stream with client communication. In fact, the TcpListener class also provides a more flexible approach to acceptsocket (), and of course the cost of flexibility is complex, and accepttcpclient () is sufficient for simpler programs. In addition, the TcpListener class provides the start () method to begin listening, providing a stop () method to stop listening.

First we use a port to initialize a TcpListener instance and start listening on port 13:

private const int portnum = 13;
tcplistener listener = new TcpListener (portnum);
listener. Start ()/Begin monitoring

If there is an unhandled connection request, use the AcceptTcpClient method for processing and get the data flow:

tcpclient client = listener. AcceptTcpClient ();
networkstream ns = client. GetStream ();

Then, get the native time and save it in a byte array, write the data stream using the Networkstream.write () method, and then the client can get this information from the data stream through the Read () method:

byte[] Bytetime = Encoding.ASCII.GetBytes (DateTime.Now.ToString ());
ns. Write (bytetime, 0, bytetime.length);
ns. Close ()//Don't forget to turn off data flow and connections
client. Close ();

The complete list of procedures for server-side programs 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 ();
}
}
£}

The above two sections of the program compiled and run, OK, we have implemented in C # based on TCP protocol network communication, how? It's simple!

Using the basic methods described above, we can easily write some very useful programs, such as FTP, email transceiver, point-to-point instant messaging and so on, you can even own a QQ to come!



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.