. NET platform under C#socket Communication (medium) __.net

Source: Internet
Author: User
Tags sessions

This article mainly describes:

1, the normal communication handshake establishment

2, a One-to-many communication

3, send receive data format conversion

4. Resource Release

5, open and maintain service monitoring

1, shake hands to establish a normal communication channel

The project needs to establish a stable channel between the two sides of the communication (assuming a host computer, a subordinate machine) for communication. The specific operation of this project is: the host computer as a server, the next computer as the client, while the development of communication protocols. The upper computer first opens the listening waiting to establish the channel, the subordinate machine actively connects the host computer and sends the successful information to the host computer, and the host computer sends the data to the lower machine according to the communication protocol, at this time the channel has been established. But for the sake of the insurance (also follow three times handshake), the client sends the data again to the host computer informs the channel to establish completes.

2. A One-to-many communication

The project demand is a host computer multiple subordinate machine, this determines the host computer as the server side, the next machine as the client active connection server. One-to-one communication with only a socket channel, so whether the host computer or the next machine in the sending and receiving data will not exist in the case of disorderly collection of data. One-to-many means that the host computer and the next opportunity to establish multiple channels, so when sending data need to record which lower computer is in which socket channel in order to make logical processing. The process of dealing with one-to-many communication in this article is:

1 first set up a dialogue class session:

public class sessions
    {public
        sockets Clientsocket {get; set;} The client's Socket public
        string ip;//the client's IP

        (socket Clientsocket)
        {this
            . Clientsocket = Clientsocket;
            This. IP = Getipstring ();
        }

        public string getipstring ()
        {
            string result = ((IPEndPoint) clientsocket.remoteendpoint). Address.tostring ();
            return result;
        }
    

2 When the socket is listening on the service side:

IPEndPoint loaclendpoint = new IPEndPoint (Ipaddress.any, Port);
            Socketlister = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);

            Socketlister.bind (Loaclendpoint);
                try {socketlister.listen (maxconnection);
                    while (isrunning) {clientsocket = Socketlister.accept ();
                    Save Socket Session NewSession = new session (Clientsocket);
                    Lock (Sessionlock) {Sessiontable.add (Newsession.ip, newsession);
                    } socketconnection socketconnection = new SocketConnection (clientsocket);
            Socketconnection.receivedatagram ()//Receive data} \ catch (SocketException ex) {
            }



Statement

Public Hashtable sessiontable = new Hashtable ();//INCLUDE client session

Private Object Sessionlock = new Object ();

In order to facilitate understanding, the entire service socket is written on the establishment of the above.

3 sending data to different clients

Hashtable ht = serversocket.sessiontable;
            foreach (Session sessions in HT. Values)
            {
                if (session). IP = = "127.0.0.1")//example
                {
                    socketconnection socketconnection = new SocketConnection (session. Clientsocket);
                    String str = "C300010002D2";
                    byte[] sendbytes = Strtohexbyte (str);
                    Socketconnection.send (sendbytes);
                }               
            

The SocketConnection class has been used several times, written in the following:

public class Socketconnection:idisposable {public ServerSocket Server {get; set;}
        Public byte[] Msgbuffer = null;
        private int totallength = 0;

        public int currentbufferlength;
        Private Socket _clientsocket = null;
        Public sockets Clientsock {get{return this._clientsocket;}

        Socketconnectiontype Type {get; private set;} #region Constructor Public socketconnection (ServerSocket server, Socket sock) {this.
            Server = server;
            This._clientsocket = sock; This.
        Type = Socketconnectiontype.server;
            Public SocketConnection (Socket sock) {this._clientsocket = sock; This.
        Type = socketconnectiontype.client; #endregion #region Events public socketconnectiondelegate OnConnect = null;//Connection Publ
 IC socketconnectiondelegate onlostconnect = null;//Interrupt Connection       Public Receivedatadelegate Onreceivedata = null;//receive data #endregion #region Connect public void Connect (ipaddress ip, int port) {this. Clientsock.beginconnect (IP, port, Connectcallback, this.)
        Clientsock); private void Connectcallback (IAsyncResult ar) {try {Socket ha Ndler = (Socket) ar.
                asyncstate; Handler.
                EndConnect (AR);
                if (OnConnect!= null) {OnConnect (this);
            } receivedatagram ();
        #endregion #region Send to catch (SocketException ex) {}}}
        public void Send (string data) {Send (System.Text.Encoding.UTF8.GetBytes (data)); public void Send (byte[] bytedata) {try {int length = Bytedata .
                Length; 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. Clientsock.beginsend (data, 0, data.) Length, 0, New AsyncCallback (Sendcallback), this.
            Clientsock); The catch (SocketException ex) {}} private void Sendcallback (Iasyncre Sult ar) {try {socket handler = (socket) ar.
                asyncstate; Handler.
            Endsend (AR); #endregion #region Receiv for catch (SocketException ex) {}}} Edatagram public void Receivedatagram () {Socketstateobject state = new Socketstateobject
            ();
            State.worksocket = _clientsocket; _clientsocket.beginreceive (state.buffer, 0, Socketstateobject.buffersize, 0, New AsyncCallback (ReceiveCallback), state); private void ReceiveCallback (IAsyncResult ar) {socketstateobject state = (socketstateobjec T) ar.
            asyncstate;
            Socket handler = State.worksocket; if (handler. Connected) {try {State.bytesread = handler.
                    EndReceive (AR); if (State.bytesread > 0) {ondatarecivedcallback (State.buffer, STATE.BYTESR
                        EAD);
                        Array.clear (state.buffer, 0, state.buffer.Length);
                        State.bytesread = 0; Handler.
                    BeginReceive (state.buffer, 0, socketstateobject.buffersize, 0, New AsyncCallback (ReceiveCallback), state); else {//
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.