C#-socket Listening Message processing

Source: Internet
Author: User
Tags ack

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. The TCP protocol is an essential part of the message command delivery in many distributed applications.

Three-time handshake for TCP communication: three-time handshake (three-way handshake), which means that the client and server are required to send a total of 3 packets when establishing a TCP connection.

    1. First handshake: The client sends a TCP SYN flag where 1 of the packet indicates the port of the server to which the client intends to connect, and the initial sequence number x, which is stored in the header sequence number (Sequence) field.
    2. Second handshake: The server sends back a confirmation packet (ACK) reply. That is, the SYN flag bit and the ACK flag bit are both 1, and the confirmation ordinal (acknowledgement number) is set to the customer's I S n plus 1 to. that is x+1.
    3. Third handshake: The client sends the confirmation packet again (ACK) to the SYN flag bit for the 0,ACK flag bit of 1. and sends the server an ACK to the ordinal field +1, which is sent to the other party in the OK field. and write +1 of the isn in the data segment.

First look at the server Socket Monitor code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Text;usingSystem.Threading;namespacesocketdome{/// <summary>    ///Handling Socket Listening Logic/// </summary>     Public classSocketprovider {Private StaticSocket Servicesocketlistener;//Socke Monitoring processing requests        /// <summary>        ///Open Socket Monitor/// </summary>         Public Static voidInit () {Servicesocketlistener=Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Servicesocketlistener.bind (NewIPEndPoint (Ipaddress.parse ("10.0.0.217"),20000));//IP and port should be configurableServicesocketlistener.listen (1024x768); Thread Handlesocket=NewThread (NewThreadStart (Handlesocket));        Handlesocket.start (); }        /// <summary>        ///Monitoring Links/// </summary>        Private Static voidHandlesocket () { while(true)            {                Try{Socket Currsocket= Servicesocketlistener.accept ();//Create a new System.Net.Sockets.Socket for a new connectionThread ProcessThread =NewThread (NewParameterizedthreadstart (Processsocket));                Processthread.start (Currsocket); }                Catch { }            }        }        /// <summary>        ///Processing Socket Information/// </summary>        /// <param name= "obj" >create a new socket object with new connection</param>        Private Static voidProcesssocket (Objectobj) {Socket Currsocket=(Socket) obj; Try            {                byte[] recvbytess =New byte[1048576]; intrecbytes; Recbytes= Currsocket.receive (recvbytess, Recvbytess.length,0); if(Recbytes >0)                {                    varContentstr = Encoding.UTF8.GetString (recvbytess,0, recbytes); var_order = Contentstr.split ('~'); byte[] Sendpass = Encoding.UTF8.GetBytes (_order[0]. ToUpper () +"#SUCCESS");//dialogue first, then go to asynchronous processingcurrsocket.send (Sendpass, Sendpass.length, Socketflags.none); Switch(_order[0]. ToUpper ()) { Case"Addcache": Console.WriteLine ("Adding cached Messages"+ _order[1]); //Handling Addcache LogicConsole.WriteLine ("Write log Logs");  Break; default: Console.WriteLine ("Command Error"); Console.WriteLine ("Write log Logs");  Break; }                }            }            Catch(Exception ex) {Console.WriteLine ("Write the error log"+Ex.            Message); }        }    }}

This service side, listens to the client to send the command, the format is defined as: command ~ parameter, after the service side receives the command message to the client immediately sends back to the command and begins processing, carries on the asynchronous processing avoids the client waits.

Below is a look at the client's socket client unsolicited service-side code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Text;namespaceconsoleapplication7{/// <summary>    ///Socket Helper/// </summary>     Public classSockethelper {Private stringIP; PrivateIPEndPoint ex; Privatesocket socket;  PublicSockethelper (stringIpintPort) {Socket=Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);  This. IP =IP;  This. ex =NewIPEndPoint (Ipaddress.parse (IP), port); }        /// <summary>        ///Socket for connection/// </summary>        /// <returns>Connection failed or successful</returns>         Public BOOLSocketlink () {Try{socket.                Connect (ex); return true; }            Catch(Exception ex) {return false; }        }        /// <summary>        ///Socket Send Message/// </summary>        /// <param name= "strmsg" >message</param>         Public voidSendvarmessage (stringstrmsg) {            Try            {                byte[] msg =System.Text.Encoding.UTF8.GetBytes (strmsg);  This. Socket.            Send (msg); }            Catch(Exception ex) { This. Socket.            Close (); }        }        /// <summary>        ///Socket Message Callback/// </summary>        /// <returns></returns>         Public stringReceiveMessage () {Try            {                byte[] msg =New byte[1048576]; intRecv =socket.                Receive (msg);  This. Socket.                Close (); returnSystem.Text.Encoding.UTF8.GetString (MSG,0, recv); }            Catch(Exception ex) { This. Socket.                Close (); return "ERROR"; }        }    }}
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceconsoleapplication7{classProgram {Static voidMain (string[] args) {Sockethelper Socket=NewSockethelper ("10.0.0.217",20000); if(socket.) Socketlink ()) {Console.WriteLine ("Connection Successful"); Socket. Sendvarmessage ("addcache~ Zhang San"); stringStrreposon =socket.                ReceiveMessage ();            Console.WriteLine (Strreposon);        } console.read (); }    }}

First, the server-side query is opened as the management Park, and then the client actively requests the server for message requests.

C#-socket Listening Message processing

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.