C # TCP study notes

Original link: http://www.cnblogs.com/finlay/archive/2013/03/10/2952517.html

TCP is a connection-oriented , reliable , transport layer protocol based on byte stream.

  • 1.TCP working process

Establish a connection: three-way handshake, transfer data, the connection is terminated.

  • 2.TCP main features

Connection-oriented, end to end communication, high reliability, full-duplex transmission method, a data transmission method in bytes, no data transmission message boundaries.

  • 3.TCP synchronous to asynchronous

When using TCP development, .NET Framework provides two modes: synchronous and asynchronous.

Synchronization works is the use of TCP execute programs written to listen or accept the statement when, before the completion of the current work is no longer continue, threads for blocking state.

Asynchronous operation mode refers to the program execution to listen or accept the statement, regardless of the current work is completed, will continue down the implementation.

About synchronous to asynchronous differences and connections, I have never understood. Synchronous execution speed (for computers), asynchronous execution is slow (but feel to the user to perform faster).

  • 4. Connection

4.1 Socket connection is established

The client part of the code:

 1 //定义变量
 2 public IPEndPoint ipEndPoint;
 3 public Socket clentSocket;
 4 public NetworkStream netStream;
 5 public Thread threadConnection;
 6 
 7 //...
 8 
 9 //初始化变量
10 ipEndPoint = new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text));
11 clentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
12 clentSocket.Connect(ipEndPoint);

  Server part of the code:

 1 //定义变量
 2 public IPEndPoint ipEndPoint;
 3 public Socket clientSocket;
 4 public Socket serverSocket;
 5 
 6 //....
 7 
 8 //初始化变量
 9  ipEndPoint = new IPEndPoint(IPAddress.Any, 65535);
10 serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
11 serverSocket.Bind(ipEndPoint);
12 serverSocket.Listen(65535);

  This approach is used to communicate using Socket.

4.2 TcpListener and establish a connection using TcpClient

The client part of the code:

1 public TcpClient tcpClient = null;
2 public NetworkStream networkStream = null;
3 
4 //....
5 
6 tcpClient = new TcpClient();
7 tcpClient.Connect(txtIP.Text, int.Parse(txtPort.Text));

  Server part of the code:

1 private TcpListener tcpLister = null;
2 private TcpClient tcpClient = null;
3 
4 //...
5 
6 tcpLister = new TcpListener(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text));
7 tcpLister.Start();

In this manner it is encapsulated using a .NET TcpClient and TcpListener to communicate.

Reproduced in: https: //www.cnblogs.com/finlay/archive/2013/03/10/2952517.html

Guess you like

Origin blog.csdn.net/weixin_30810583/article/details/94921430