C#socket communication under the. NET Platform (ON)

Source: Internet
Author: User

is completely basic, novice can feel free to see, Daniel can close browse page, haha.

Before starting the introduction of the Socket to supplement the basic knowledge, on the basis of understanding the network communication will be logical, of course, the foundation can be skipped. It's all nonsense, get into the chase.

Tcp/ip:transmission Control protocol/internet Protocol, TCP/IP protocol, also known as Network Communication protocol. Simply put: TCP controls the transmission of data, is responsible for the discovery of transmission problems, once a problem is signaled, the need to re-transmission, until all data safe and correctly transmitted to the destination, and IP is responsible for each computer in the Internet to define an address for transmission. From the aspect of protocol layering model: TCP/IP consists of: network interface layer (link layer), Network layer, Transport layer, application layer. It is different from the OSI seven-layer structure and for the protocol family, which simply means:

Note: The four-layer structure of TCP/IP corresponds to the OSI seven-layer structure on the left.

The middle diagram: The location of the TCP/IP protocol family in the OSI seven layer and its corresponding functions.

Right: The TCP/IP Protocol module diagram.

At this stage of the socket communication using TCP, UDP protocol, relative to UDP, TCP is a more secure and stable protocol. This article only involves the TCP protocol for socket communication. First of all, the TCP/IP three handshake, extending the basic process of socket communication on the basis of handshake.

Here are some of the most notorious three-time handshakes that are familiar to graduates of graduate interviews:

1 The client sends the SYN message to the server side and sends the sequence number x.

2 The server side receives the request message sent by the client, then sends the SYN message to the client, and sends the confirmation ordinal x+1, and sends the serial number as Y.

3 After the client receives the acknowledgement message from the server, it sends the confirmation signal y+1, and the sending sequence number is Z. This connects to the client and server side.

On this basis, the socket connection process:

Server monitoring: The server-side socket does not locate the specific client socket, but is waiting for the listening state, real-time monitoring network status.

Client Request: The client Clientsocket sends a connection request, and the target is the serversocket of the server. To do this, clientsocket must know the address and port number of the ServerSocket, making a connection request for the scan.

Connection confirmation: When the server socket is heard or is a connection request from the client socket, the server responds to the client's request, suggests a new socket, sends the server socket to the client, and once the client confirms the connection, the connection is established.

Note: During the connection confirmation phase: The server socket can still receive connection requests from other clients even after it has established a connection with a client socket, which is the cause of the one-to-many generation.

Simply describe the connection process:

The socket connection principle is known, and the most basic and simplest socket communication is written here:

Server-side:

int port = 6000;            String host = "127.0.0.1";            IPAddress IP = ipaddress.parse (host);            IPEndPoint ipe = new IPEndPoint (IP, port);            Socket ssocket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);            Ssocket.bind (IPE);            Ssocket.listen (0);            Console.WriteLine ("Listening is turned on, please Wait");            Receive Message Socket ServerSocket = Ssocket.accept ();            Console.WriteLine ("Connection established");            String recstr = "";            byte[] RecByte = new byte[4096];            int bytes = Serversocket.receive (recbyte, recbyte.length, 0);            Recstr + = Encoding.ASCII.GetString (recbyte, 0, bytes);            Send Message Console.WriteLine ("Server-side Access information: {0}", RECSTR);            String sendstr = "Send to Client:hello";            byte[] Sendbyte = Encoding.ASCII.GetBytes (SENDSTR);            Serversocket.send (Sendbyte, sendbyte.length, 0);           Serversocket.close (); Ssocket.close (); 

Client:

int port = 6000;            String host = "127.0.0.1";//server-side IP address            IPAddress IP = ipaddress.parse (host);            IPEndPoint ipe = new IPEndPoint (IP, port);            Socket clientsocket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);            Clientsocket.connect (IPE);            Send Message            string sendstr = "Send to Server:hello,ni Hao";            byte[] sendbytes = Encoding.ASCII.GetBytes (SENDSTR);            Clientsocket.send (sendbytes);            Receive Message            string recstr = "";            byte[] recbytes = new byte[4096];            int bytes = Clientsocket.receive (recbytes, recbytes.length, 0);            Recstr + = Encoding.ASCII.GetString (recbytes, 0, bytes);            Console.WriteLine (RECSTR);            Clientsocket.close ();


The above-mentioned server and client establish communication, the communication will end after sending one message to each other, and in the project of the people, such communication certainly can not meet the demand. It then introduces asynchronous communication, which simply means that the server side and the client can communicate with each other more than once, without worrying that the channel will shut down. When it comes to asynchronous communication, the client-server connection is the same as the synchronous communication described above, where only the server-side and the client send the information and the methods to receive the information are written. (The method of sending and receiving the server-side and the client is the same)

First write the asynchronous connection method:

public void Connect (IPAddress ip, int port)        {            this.clientSocket.BeginConnect (IP, Port, new AsyncCallback ( Connectcallback), this.clientsocket);        }        private void Connectcallback (IAsyncResult ar)        {            try            {                Socket handler = (socket) ar. asyncstate;                Handler. EndConnect (AR);            }            catch (SocketException ex)            {}        }

Send Information method:

 public void Send (string data) {Send (System.Text.Encoding.UTF8.GetBytes (data)); } private void Send (byte[] bytedata) {try {int length = Bytedata.leng                Th                Byte[] head = bitconverter.getbytes (length); byte[] data = new Byte[head.                Length + bytedata.length]; Array.copy (head, data, head).                Length); Array.copy (bytedata, 0, data, head.                Length, bytedata.length); This.clientSocket.BeginSend (data, 0, data.            Length, 0, New AsyncCallback (Sendcallback), this.clientsocket);             } catch (SocketException ex) {}} private void Sendcallback (IAsyncResult ar) { try {Socket handler = (socket) ar.                asyncstate; Handler.            EndSend (AR); } catch (SocketException ex) {}} 

How to receive information:

public void Receivedata () {clientsocket.beginreceive (msgbuffer, 0, msgbuffer.length, 0, new Asynccallba        CK (receivecallback), null); } private void ReceiveCallback (IAsyncResult ar) {try {int REnd = Clie                Ntsocket.endreceive (AR);                    if (REnd > 0) {byte[] data = new Byte[rend];                    Array.copy (msgbuffer, 0, data, 0, REnd); Data can be processed on demand at this time clientsocket.beginreceive (msgbuffer, 0, msgbuffer.length, 0, new AsyncCallback (recei                Vecallback), NULL);                } else {Dispose ();            }} catch (SocketException ex) {}} private void Dispose () {                try {this.clientSocket.Shutdown (socketshutdown.both);            This.clientSocket.Close (); } CATCH (Exception ex) {}} 

Asynchronous problem solved, and then write a self in the use of the process is often a problem. Received packet processing problem: In network communication, using asynchronous communication, then the client in the receiving server to send the packet processing will have some trouble, such as sticky packets, broken packets, this is a small problem, here simply write your own way to deal with this problem.
Sticky Pack Handling:

Public Hashtable DataTable = new Hashtable ()//Because the data sent by multiple servers (IP) is received here, the data is sent separately from the IP address, public void dataarrial (byte[]                    Data, String IP) {try {if (Data.length < 12)//To be judged as required {                        Lock (DataTable) {if (Datatable.contains (IP))                            {Datatable[ip] = Data;                        Return }}} if (data[0]! = 0x1F | |                        DATA[1]! = 0xF1)//Flag bit (written as required) {if (Datatable.contains (IP)) { if (DataTable = null) {byte[] OldData = (byte[]) datata                                ble[ip];//Remove sticky packet data if (olddata[0]! = 0x1F | | olddata[1]! = 0xF1) {                            Return        }                    byte[] NewData = new Byte[data.length + olddata.length];                            Array.copy (olddata, 0, NewData, 0, olddata.length); Array.copy (data, 0, NewData, Olddata.length, data.length);//A new array of data, first-to-last data in front, and back-to-back data behind Lock (D                            atatable) {DATATABLE[IP] = null;                            } dataarrial (NewData, IP);                        Return                }} return;                } int revdatalength = data[2];//The length of the data to be sent int revcount = data.length;//received data length if (Revcount > Revdatalength)//If the received data length is greater than the length of the data sent, it indicates that there are multiple frames of data, continue processing {byte[] Otherdata                    = new Byte[revcount-revdatalength];                    Data.copyto (Otherdata, revCount-1); Array.copy (Data, Revdatalength, Otherdata, 0, Otherdata.length);                    data = (byte[]) Redim (data, revdatalength);                Dataarrial (Otherdata, IP); if (Revcount < revdatalength)//The received data is less than the length to be sent {if (Datatable.conta                    INS (IP)) {DATATABLE[IP] = data;//Update the current sticky packet data return;         }}//Here can be processed on demand} catch (Exception ex) {}  } private array Redim (array origarray, Int32 desizedsize) {//acknowledgment of the type of each element types T = Origarray.gettype ().            GetElementType ();            Create a new array containing the number of expected elements//new array type must match the type of array newarray = Array.CreateInstance (t, desizedsize);            Copies the elements from the original array to the new array.            Array.copy (Origarray, 0, NewArray, 0, Math.min (origarray.length, desizedsize));        Returns the new array return newarray; }


Socket the most basic content finally finished, combined with the above information for a simple application should be no problem, but if it involves the communication problem of the comparison service, its solution needs to delegate, multi-threading, interface knowledge, which is recently learning, recently has a sentiment: The delegation is. NET C # The most basic and important part of it, it should be learned.

Spit Groove: A delegate is not scary, terrible is a number of delegates, and the delegate is the most terrible to apply the delegate.

Hey, learn it slowly. Maybe it will be written in one weeks or one months, maybe longer.

C#socket communication under the. NET Platform (ON)

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.