C # using the server to achieve communication between clients _ practical skills

Source: Internet
Author: User
Tags readline

First to tell me about the entire socket communication process understanding, after all, beginners, say wrong forgive, know wrong will correct ~

First, create a new serversocket on the service side, initialize it (generally contains ADDRESSFAMILY:IP address type, sockettype:socket transmit data way, ProtoType: Transmission protocol);

Then we set up the server-side ip:port to bind, and then start listening and set up the number of client listeners simultaneously.

At this point, the server is waiting until a certain client connects to the Ip:port, then serversocket.accept () works to get the connection. (At this point the connection is the address of the information Oh!) Remember to save it)

Once the connection has been made, the server can communicate with the client, and when the second client (which we call CLIENTB) is added, the server receives the CLIENTB message. This message can be forwarded to the previous client (we call it Clienta) and can be sent to CLIENTB when the message is Clienta. This enables the communication between the clients. (Focus on saving connection information!!) )

So now put the code to explain:

Server-side code

Namespace Socketserver {class Program {private static byte[] result = new byte[1024];
    Static Socket ServerSocket;
    private static string client;
    private static Socket Clientsocket; I have saved two client, because my computer opened two client, not much//theoretically should open a socket[] to save information, it is best to use a two-tuple to bind the client's information and connections/
    This can be disconnected after the next landing or can be identified is this client private static Socket clientsocketa=null;
    
    private static Socket Clientsocketb=null;
    static void Main (string[] args) {program.setport (8885); private static void Setport (int port) {IPAddress IP = ipaddress.parse ("127.0.0.1");//set IP ServerS Ocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);//initialize ServerSocke
      T.bind (New IPEndPoint (IP, port));//bind Serversocket.listen (10);
      Into the Listening state Console.WriteLine ("Monitor {0} successfully", serverSocket.LocalEndPoint.ToString ());
 Open a thread to listen for client connection thread mythread = new Thread (listenclientconnect);     Mythread.start ();

    Console.ReadLine ();
      ///<summary>///Listener Client connection///</summary> private static void Listenclientconnect () {

        while (true) {//client The connection after the connection Clientsocket = Serversocket.accept ();
        Here I have only two client, so I simply wrote if (Clientsocketa = = null) {Clientsocketa = Clientsocket;
        else if (CLIENTSOCKETB = null) {CLIENTSOCKETB = Clientsocket;
            else {//when one of them is disconnected and reconnected again, you need to save the connection if (Clientsocketb.isbound) {
            Clientsocketa = CLIENTSOCKETB;
          CLIENTSOCKETB = Clientsocket;
            else {Clientsocketb = Clientsocketa;
          Clientsocketa = Clientsocket;
        } clientsocket.send (Encoding.ASCII.GetBytes ("Say hello")); Open thread receive client information thread Receivedthread = new Thread (ReceivemessaGE);

      Receivedthread.start (Clientsocket); } private static void ReceiveMessage (object clientsocket) {socket myclientsocket = (socket) Clien
      
      Tsocket;
          while (true) {try {int revceivenumber = myclientsocket.receive (result); Console.WriteLine ("Accept client {0} message {1}", myClientSocket.RemoteEndPoint.ToString ()//, Encoding.ASCII.GetString (res
          Ult, 0, Revceivenumber));
          Console.WriteLine (Encoding.ASCII.GetString (result, 0, revceivenumber));
            if (Myclientsocket = = Clientsocketa) {Console.WriteLine ("Receive from A");
              if (Clientsocketb!=null&&clientsocketb.isbound) {Console.WriteLine ("A is BOUND");
            Clientsocketb.send (result, 0, Revceivenumber, socketflags.none); else {myclientsocket.send Encoding.ASCII.GetBytes ("The People is not online! Send Failed! ")); Console.WriteLine ("The Other side is not online, send failure!")
            ");
            } else {Console.WriteLine ("Receive from B");
              if (Clientsocketa!= null && clientsocketa.isbound) {Console.WriteLine ("A is BOUND");
            Clientsocketa.send (result, 0, Revceivenumber, socketflags.none); else {myclientsocket.send Encoding.ASCII.GetBytes ("The People is not online!
              Send failed! ")); Console.WriteLine ("The Other side is not online, send failure!")
            "); '} ' catch (Exception ex) {Console.WriteLine (ex).
          message);
          Myclientsocket.shutdown (Socketshutdown.both);
          Myclientsocket.close ();

        Break

 }
      }

    }
  }
}

Client-side code (because it's almost always just one)

Namespace Socketclient {class Program {private static byte[] result = new byte[1024];
    private static Socket Clientsocket;
        private static void Listenserver () {while (true) {result = new byte[1024];
        
        int receivelength = clientsocket.receive (result);
      Console.WriteLine ("{0}", Encoding.ASCII.GetString (result, 0, receivelength));
      } static void Main (string[] args) {IPAddress ip = ipaddress.parse ("127.0.0.1");
      Clientsocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);
        try {clientsocket.connect (IP, 8885); Console.WriteLine ("Connection Successful!")

      "); catch (Exception e) {Console.WriteLine ("Connection Failed!")
        ");
      Return
      Thread threadread = new Thread (listenserver);
     

      Threadread.start ();
          while (true) {try {thread.sleep (1000); String SendMessage = COnsole.
          ReadLine ();
          
        Clientsocket.send (Encoding.ASCII.GetBytes ("Sylvia:" +sendmessage));
          catch (Exception ex) {Clientsocket.shutdown (Socketshutdown.both);
          Clientsocket.close ();
        Break
      } Console.WriteLine ("Send finished press ENTER Exit");
    Console.readkey ();

 }
  }
}

When writing to pay special attention to send information, note that byte[] transmission size, it is easy to become a byte[of the size of the array rather than the size of the content.

Let's try it on your own.

The above is the entire content of this article, 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.