The basic course of C # server-side and client communication programming based on TCP protocol _c# tutorials

Source: Internet
Author: User
Tags getstream socket

Common network application protocols running on top of TCP are HTTP, FTP, SMTP, POP3, IMAP.
TCP is the most important transport protocol in the TCP/IP system, and it provides full duplex and reliable delivery service, which is the foundation of most application protocol work.
TCP is a kind of connection-oriented, reliable, traffic-layer communication protocol based on byte stream.

The working process of TCP

    • Establish a connection
    • Transfer data
    • Termination of connection


main features of TCP
1.TCP is a connection-oriented protocol
2. is end-to-end communication. There can be only two endpoints per TCP connection, and only one-to-one communication, not multiple
of direct communication
3. High reliability
4. Full Duplex mode transmission
5. Data is transmitted in a byte-stream manner
6. Transmission of data without message boundaries

About Threads
when developing an application with TCP, the. NET Framework provides two ways to work, one is how to work synchronously, and the other is how to work asynchronously.
Synchronization works by using a program written by TCP to monitor or receive statements, no longer before the current work is completed.
Continue down, the thread is blocked until the statement is complete before the next statement can proceed.
Asynchronous work means that when a program executes to listen or receive statements, it continues to execute, regardless of whether the current work is completed or not.

Common methods and properties of TcpListener and TcpClient classes

The TcpListener class is used to listen for client connection requests, and the TcpClient class is used to provide connection information for local hosts and remote hosts.
All two classes are located under the System.Net.Socckets namespace.

A common method for 1.TCPListener classes:

(1) AcceptSocket: Receive a connection from the port and give it a socket object
(2) AcceptTcpClient: Receive a connection from the port and give it TcpClient object
(3) Equals: Determine if two TcpListener objects are equal
(4) GetType: Gets the type of the current instance
(5) Pending: Determine if there is a pending connection request
(6) Start: To begin answering incoming connection requests
(7) Stop: Turn off the listener
(8) ToString: Creating a string representation of a TcpListener object


2.TcpClient Common Properties and methods
Property:
(1) Client: Gets or sets the underlying socket
(2) Lingerstate: Gets or sets the time that a socket remains connected
(3) Nodelay: Gets or sets a value that prohibits delay when the send or receive cache flushes are not full
(4) Receivebuffersize: Gets or sets the size of the TCP receive buffer
(5) Receivetimetut: Gets or sets the timeout time for socket to receive data
(6) Sendbuffersize: Gets or sets the size of the TCP send buffer
(7) Sendtimeout: Gets or sets the timeout time for socket send data

Method:
(1) Close: Frees the TcpClient instance without closing the underlying connection
(2) Connect: Connecting a client to a TCP host with the specified host name and port number
(3) BeginConnect: Asynchronous request to start a remote host connection
(4) GetStream: Gets the NetworkStream object that can send and receive data

General steps for TCP programming
1. The most basic premise of network communication is that the client should establish a TCP connection with the server first.
2. The server should continuously monitor whether the client has a connection request, and the server can identify a specific client
3. Connect and create the corresponding socket
4. Send data and receive data


General steps for writing server-side programs
1. Create a TcpListener object, and then call the object's Start method to listen on the specified port
2. In a separate thread, The first loop calls the AcceptTcpClient method to receive a connection request from the client
, obtains the TcpClient object corresponding to the client from the return result in the method, and uses the GetStream method of the object
to get NetworkStream. The object is then used to get other more convenient
objects, such as BinaryReader objects, binarywrite objects, to prepare for further communication with the other.
3. Each get a new TcpClient object, create a thread that corresponds to the customer, and the threads communicate with the corresponding
customer.
4. Determine whether to close the connection to the customer based on the information sent.

Using System; 
Using System.Collections.Generic; 
Using System.ComponentModel; 
Using System.Data; 
Using System.Drawing; 
Using System.Linq; 
Using System.Text; 
Using System.Windows.Forms; 
Using System.Threading; 
Using System.Net.Sockets; 
Using System.Net; 
 
Using System.IO; namespace TCP {public partial class Tcplistenertest:form {public tcplistenertest () {Initializ 
    Ecomponent (); }//Declare private ipaddress localaddress;//IP address IPAddress class under the namespace using system.net Private Const int port = 5  8080;//Port private TcpListener tcplistener;//listener socket Tcplestener and TcpClient class is private under namespace using System.Net.Sockets TcpClient tcpclient;//server connects with client private NetworkStream newworkstream;//uses NetworkStream objects to send or receive data from remote hosts \ Privat E BinaryReader binaryreader;//Read BinaryReader and BinaryWriter class in the namespace using System.IO under private BinaryWriter binarywrite;//write into the private void Form1_Load (object sender, EventArgs e) {ipaddress[] LiStenerip = dns.gethostaddresses ("www.baidu.com");/return the IP address specified by the host localaddress = listenerip[0];  
 
      Initialize IP address to local address TcpListener = new TcpListener (localaddress,port);//Create TcpListener object Tcplistener.start ();/start listening Thread thread = new Thread (acceptclientconnect);//Start a threads to receive request thread.  
        Start ();//Start thread}//Initiate request private void Acceptclientconnect () {while (true) {try {tcpclient = Tcplistener.accepttcpclient ()//Receive a connection from the port and give it TcpClient object if (TcpClient!= n 
            ull) {Newworkstream = Tcpclient.getstream (); 
            BinaryReader = new BinaryReader (newworkstream); 
          BinaryWrite = new BinaryWriter (newworkstream); 
        The catch {break; 

 } 
      } 
    } 
  } 
}

TCP Programming Client general steps
1. Create a TcpClient object using the TcpClient constructor
2. Connect with the server by using the Connect method
3. The network flow is obtained by using the GetStream object of the TcpClient object, and then the data is transmitted to the server using the network Flow
4. Creates a thread that listens on the specified port, loops over and processes the information sent by the server.
5. After completing the work, you want the server to send shutdown information and shut down the connection to the server.

Using System; 
Using System.Collections.Generic; 
Using System.ComponentModel; 
Using System.Data; 
Using System.Drawing; 
Using System.Linq; 
Using System.Text; 
Using System.Windows.Forms; 
Using System.Net.Sockets; 
Using System.Net; 
 
Using System.IO; namespace TCP {public partial class Tcpclienttest:form {public tcpclienttest () {initializecom 
    Ponent (); Private TcpClient tcpclient;//Declare private ipaddress IADRESS;//IP address Private const int port=58080; Port Private NetworkStream networkstream;//network stream private BinaryReader binayread;//read private BinaryWriter Bi Naywrite;//writes to the private void Tcpclient_load (object sender, EventArgs e) {ipaddress[] IPAddress = Dns.getho Staddresses ("www.baidu.com");/return the IP address specified by the host iadress = Ipaddress[0]; Initializes the IP address to the local address ipendpoint ipoint = new IPEndPoint (iadress,port);//The network endpoint is represented as IP and port number tcpclient = new TcpClient (i Point),//Instantiate TcpClient class//most convenient tcpclient TCPCLIent=new tcpclient ("www.baidu.com", port); if (tcpclient!= null) {NetworkStream = Tcpclient.getstream ();//Get network stream binayread = new BinaryRead 
        ER (networkstream); 
      Binaywrite = new BinaryWriter (NetworkStream); } private void Remessage () {while (true) {try {string RcM 
          sg = binayread.readstring ();//read data from Network stream if (rcmsg!= null) {MessageBox.Show (rcmsg); 
          } else {break; 

 } and Catch {}}}}

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.