Example code for TCP communication of C # socket _c# Tutorial

Source: Internet
Author: User
Tags getstream port number

TCP Communication for sockets

The communication principle of socket

The server-side steps are as follows.

(1) Establish a server-side socket and start listening for connection requests across the network.

(2) When a connection request from a client is detected, the client is sent the information to receive the connection request and a connection is established with the client.

(3) When the communication is complete, the server closes the socket connection to the client.

The steps for the client are as follows.

(1) Establish the socket of the client, determine the host name and port of the server to which you want to connect.

(2) Send the connection request to the server, and wait for the server feedback information.

(3) When the connection is successful, the data is interacted with the server.

(4) After the data processing, close its own socket connection.

Second, the socket communication mode

There are two types of socket communication: synchronous and asynchronous

How to work synchronously:

When a program executes to send, receive, and listen to a statement using a TCP protocol, it is blocked until the statement is completed, and the next statement is not resumed until it completes a work.

Asynchronous working mode

When a program executes to send, receive, and listen to a statement, it continues to execute, regardless of whether or not the work is completed.

C # Implementation of socket

1.1. Sync:

Server-Side client communication

After the connection to the server is established, we can send and receive data through this connection. Ports and ports transmit data in streams, because almost any object can be saved to the stream, so you can actually transfer any type of data between the client and the server. To the client, the data is written to the stream, the data is sent to the server, the data is read from the stream, and the data is received from the service side. For the server, the data is written to the stream, that is, the data is sent to the client, the data is read from the stream, and the data is received from the client.

Service side:

(1) The server listens to the port:

Server side to establish a socket, set up the IP and listening to the port and socket to bind, start listening to the connection request, when the connection request, send confirmation, establish a connection with the client, start communication with the client.

TcpListener Listener =new TcpListener (New IPEndPoint (Ipaddress.parse (IP), port);//IP for server IP address, port for listening ports

Listener.start ()/Open Monitor

(2) Detecting connection requests from the client

TcpClient remoteclient = listener. AcceptTcpClient ();
The receiving client here embodies the meaning of synchronization, and if the client initiates a connection to the server, the program waits (blocks) here until there is a client connection request

(3) data stream of the established and connected client (transmit data)

NetworkStream streamtoclient = Remoteclient.getstream ();

The data stream is used to receive and send data, synchronization is also divided into multiple clients and a single client, if the details of the point, there is a client and a number of data, if it is a single client of multiple data, connect the client, in the establishment of data flow before adding a loop on it, If it is more than one client, add a loop to the front (2). In order to receive data efficiency, it is recommended that either synchronous or asynchronous, the server is made into threads, see demo

(4) Receive the data sent over by the client (with the cache to receive)

byte[] buffer = new Byte[buffersize]; BufferSize for the size of the cache

 int bytesread; 

 Try

 {

  Lock (streamtoclient)//To ensure data integrity and security lock data flow

   {

     bytesread = streamtoclient.read (buffer, 0, buffersize);

} 

(5) Sending data to a connected client

Lock (Streamtoclient)

           {

           streamtoclient.write (buffer, 0, buffer.) Length);//buffer for sent character array         

} 

(6) release of the data stream and TcpClient (for next data and the client to send and receive)

Streamtoclient.dispose ()//releasing data in the data stream

 remoteclient.close ()//releasing TcpClient instance 

Client

(1) Connecting to the server

TcpClient TCP = new TcpClient ();

Tcp. Connect (ip,port);//Connect

if (TCP) based on the server's IP address and listening port. Connected)

{

//connection successful message mechanism see demo

Showgetdata ("Successfully connected to server:", this.strIP.Text.ToString ());
 

 } 

It should be noted here that either the use of a parameterized constructor to connect to the server, or the Connect () method to establish a connection with the server, is the synchronization method (or blocking, English block). It means that the client is unable to continue the subsequent operation until the connection to the server is successful, the method returns, or the service is not saved, thus throwing an exception. There is also a method named BeginConnect () that implements an asynchronous connection so that the program is not blocked and can immediately perform subsequent operations because the connection may take a long time to complete due to problems with network congestion. Network programming has a lot of asynchronous operation, everything is from simple to difficult, about asynchronous operation, we discuss later, now only look at the synchronization operation.

(2) Establish the data stream of the connection server

 
 

(3) Receiving and sending data

Send string

byte[] buffer = Encoding.Unicode.GetBytes (msg);//msg sent string  

 try

     {

       Lock (streamtoserver)
      {

      streamtoserver.write (buffer, 0, buffer.) Length);   Send to Server

       }

     //Receive string
       buffer = new Byte[buffersize];
       Lock (Streamtoserver)

      {

        bytesread = streamtoserver.read (buffer, 0, buffersize);

      }

 

1.2. Asynchronous

Relative to synchronization, in asynchronous connection, receive and send data method is different, have a callback function, even if can not connect or receive data, the program will continue to execute, if connected or received data, the program will return to the place where the callback function to carry out again. See below for details:

Server:

1, open the Listening interface

Private TcpListener listener;        Listener class

listener = new TcpListener (New IPEndPoint (Ipaddress.parse (IP), port);

Listener. Start ()//open listening, no limit to the number of connected clients

Or

 
 

2. Receiving Client

Listener. Beginacceptsocket (clientconnect, listener);//Asynchronous Accept client's connection request Clientconnect as a connection callback function

     <summary>

    ///receive callback function

    ///</summary>

    ///<param name= "ar" ></param>

    private void Clientconnect (IAsyncResult ar)

    {

    try

      {
        TcpListener listener = (tcplistener) ar. asyncstate;
        Accept the client's connection, get the connected socket
        Socket client = listener. Endacceptsocket (AR);

      }

      Catch {}

    

3, receive the data sent by the client

<summary> 

///Asynchronous receive data

 ///</summary>

 private void Receivedata (Socket client)

{

   // Call the asynchronous method beginreceive to tell the socket how to receive the data
  IAsyncResult IAR = client. BeginReceive (buffer, 0, bagsize, Socketflags.none, out errorcode, receivecallback, buffer);

      }

    <summary>

    ///Receive data callback function

    ///</summary> 

    ///<param name= "AR" ></param>

    private void ReceiveCallback (IAsyncResult ar)

    {     
        //Received data length.}
        int recelen = 0;

        Try

        {
          Recelen = client. EndReceive (AR, out errorcode);        

if (Recelen > 0)

         {
           onreceivedata (client);//processing function after receiving data

          }
       catch {   }

      }
      else {}

    } 

4, after the receipt of success, postback data to the client

<summary>

///Asynchronous Send message
///</summary>

 ///<param name= "Data" ></param>
 private void Onreceivedata (socket socket)

{
     string strlogin = "Succeed Recived";

byte[] data = Encoding.ASCII.GetBytes (strlogin);

 Socket. BeginSend (data, 0, data.) Length, Socketflags.none, out errorcode, sendcallback, socket);//asynchronously send data

     }

      else

      {}

    }

///< Summary>

 ///Asynchronous Send callback event

 ///</summary>

 ///<param name= "ar" ></param>

private void Sendcallback (IAsyncResult ar)

    {

socket. Endsend (AR, out errorcode);

      

Client

1, connect the server

Private TcpClient Tcpcz = null

 Tcpcz = new TcpClient ()

 Tcpcz. BeginConnect (IPAddress, Convert.ToInt32 (Port), new AsyncCallback (Connectcallback), tcpcz);//asynchronously connect to server based on server's IP address and port number

 ///<summary>

///callback functions for asynchronous connections

 ///</summary>

 ///<param name= "AR" ></param>

 private void Connectcallback (IAsyncResult ar)

    {

      TcpClient t = (tcpclient) ar. asyncstate;

      Try

      {

        if (t.connected)

        {

          t.endconnect (AR);//function to run here to show that the connection succeeded

        }

        else

        {

        }

      }

      catch () {  }

    } 

2. Send and receive strings

NetworkStream stream = tcp. GetStream ()///The data stream

        /send string

  Strlogin = "This is socket example" created on the server connection;

  byte[] data = Encoding.ASCII.GetBytes (strlogin);

 Stream. BeginWrite (data, 0, data.) Length, New AsyncCallback (Sendcallback), stream);//asynchronously Send data

 //Receive string

  byte[] result = new byte[tcp. Available]; Tcp. Available to the accepted string size

  try

 {

   stream. BeginRead (result, 0, result. Length, New AsyncCallback (Readcallback), stream);//Asynchronous Accept Server return string

  }

    catch {} string

    strresponse = Encoding.ASCII.GetString (Result). Trim ()///string received from the server

 }

  \

     catch ()

     {

     }

   } 

The above is a period of time on the socket some of the experience, I hope to help you learn, but also hope that we support the cloud habitat community.

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.